im正在尝试连接两个表。我只想连接第一个匹配的行,其他行必须为null。
其中一个表包含每个User
的每日记录,第二个表包含每一个用户和每一天的目标。
联接的结果表应仅联接User
和Day
的第一个实例,并将其他实例设置为null
。联接表中的目标可以解释为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,子查询,但我找不到方法。这可能吗?
一个选项使用窗口函数:
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