我有这个子查询结果:
DATE REGCODE REGCODE2 REGCODE 3 REGCODE4
02/01/15 70771 5 6 8
02/01/15 null 5 21 8
02/01/15 70855 4 5 13
02/01/15 null ... ... ...
03/01/15 70771
03/01/15 70772
05/01/15 null
05/01/15 70855
05/01/15 70826
我需要按日期计算不同的REGCODEs
分组,但如果其中一个在上一个日期重复,则不再计算
所以,我需要这样的东西:
DATE COUNT(REGCODE)
02/01/15 2
03/01/15 1
05/01/15 1
非常感谢你的帮助。
答案 0 :(得分:3)
SELECT t.date, COUNT(DISTINCT t.regcode)
FROM yourtable t
WHERE NOT EXISTS (
SELECT 1
FROM yourtable prev
WHERE prev.regcode=t.regcode
AND prev.date<t.date
)
GROUP BY t.date;
(可能需要注册码,日期索引)
答案 1 :(得分:0)
试试这个。它使用ROW_NUMBER()
和PARTITION BY
使用REGCODE
。
declare @table table ([DATE] date, REGCODE int)
insert into @table
select '02/01/15', 70771 union
select '02/01/15', null union
select '02/01/15', 70855 union
select '02/01/15', null union
select '03/01/15', 70771 union
select '03/01/15', 70772 union
select '03/01/15', null union
select '05/01/15', 70855 union
select '05/01/15', 70826
select [DATE], COUNT([DATE]) from
(
select [DATE], REGCODE,
row_number() over (partition by REGCODE order by [DATE]) rn
from @table
) e
where rn = 1 and regcode is not null
group by [DATE]