我有两张桌子 表1
个人号码 | 其他值 |
---|---|
1 | |
2 |
表2
个人 | 日期 |
---|---|
1 | 2023-09-1 |
2 | 2023-09-1 |
2 | 2023-09-2 |
我想要一个选择,为我提供一个表,如果当天有条目存在,则设置 1,如果不存在,则设置 0 预计会是
个人号码 | 2023-09-01 | 2023-09-02 |
---|---|---|
1 | 1 | 0 |
2 | 1 | 1 |
我尝试了以下方法,但得到的 1 和 0 不正确
SELECT t1.personalnr,
case when EXISTS ( select* from table2
where date between '2023-01-09' and '2023-02-09' and t1.personalnr = t2.personalnr) then '1' else '0'
end
case when EXISTS ( select* from table2
where date between '2023-02-09' and '2023-03-09' and t1.personalnr = t2.personalnr) then '1' else '0'
end
FROM [BKLatWORK].[dbo].[Table1] t1
left join table2 t2 on t2.PersonalNr = t1.PersonalNr
group by t1.PersonalNr, t2.personalnr
如果您不寻找动态解决方案,可以使用条件聚合:
select t1.Personalnr,
count(case when t2.Date = '2023-09-01' then 1 end) as '2023-09-01',
count(case when t2.Date = '2023-09-02' then 1 end) as '2023-09-02'
from table1 t1
inner join table2 t2 on t1.Personalnr = t2.Personalnr
group by t1.Personalnr