仅在第一场比赛中加入记录
Join records only on first match
我正在尝试加入两个 table。我只想加入第一个匹配行,其他行必须为空。
其中一个 table 包含每个 User
的每日记录,第二个 table 包含每个用户和每一天的目标。
拼接结果table应该只拼接第一次出现的User
和Day
,其他设置为null
。加入的 table 中的目标可以解释为 DailyGoal
.
示例:
Table1 Table2
Id Day User Value Id Day User Goal
================================ ============================
01 01/01/2020 Bob 100 01 01/01/2020 Bob 300
02 01/01/2020 Bob 150 02 02/01/2020 Carl 170
03 01/01/2020 Bob 50
04 02/01/2020 Carl 200
05 02/01/2020 Carl 30
ResultTable
Day User Value Goal
============================================
01/01/2020 Bob 100 300
01/01/2020 Bob 150 (null)
01/01/2020 Bob 50 (null)
02/01/2020 Carl 200 170
02/01/2020 Carl 30 (null)
我尝试执行 top1、distinct、子查询,但我无法找到执行此操作的方法。这可能吗?
一个选项使用 window 函数:
select t1.*, t2.goal
from (
select t1.*,
row_number() over(partition by day, user order by id) as rn
from table1 t1
) t1
left join table2 t2 on t2.day = t1.day and t2.user = t1.user and t1.rn = 1
一个case
表达式更简单:
select t1.*,
case when row_number() over(partition by day, user order by id) = 1
then t2.goal
end as goal
from table1 t1
我正在尝试加入两个 table。我只想加入第一个匹配行,其他行必须为空。
其中一个 table 包含每个 User
的每日记录,第二个 table 包含每个用户和每一天的目标。
拼接结果table应该只拼接第一次出现的User
和Day
,其他设置为null
。加入的 table 中的目标可以解释为 DailyGoal
.
示例:
Table1 Table2
Id Day User Value Id Day User Goal
================================ ============================
01 01/01/2020 Bob 100 01 01/01/2020 Bob 300
02 01/01/2020 Bob 150 02 02/01/2020 Carl 170
03 01/01/2020 Bob 50
04 02/01/2020 Carl 200
05 02/01/2020 Carl 30
ResultTable
Day User Value Goal
============================================
01/01/2020 Bob 100 300
01/01/2020 Bob 150 (null)
01/01/2020 Bob 50 (null)
02/01/2020 Carl 200 170
02/01/2020 Carl 30 (null)
我尝试执行 top1、distinct、子查询,但我无法找到执行此操作的方法。这可能吗?
一个选项使用 window 函数:
select t1.*, t2.goal
from (
select t1.*,
row_number() over(partition by day, user order by id) as rn
from table1 t1
) t1
left join table2 t2 on t2.day = t1.day and t2.user = t1.user and t1.rn = 1
一个case
表达式更简单:
select t1.*,
case when row_number() over(partition by day, user order by id) = 1
then t2.goal
end as goal
from table1 t1