总结许多时间间隔内的天数

时间:2012-01-16 19:49:17

标签: sql sql-server sql-server-2005 sum datediff

我有下表:

CREATE table DataDiff (CLI tinyint, id tinyint, date datetime, countable bit)
insert into DataDiff values (234,1,convert(datetime,'17/12/1997',103),1)
insert into DataDiff values (234,2,convert(datetime,'09/07/1998',103),0)
insert into DataDiff values (234,3,convert(datetime,'11/08/1998',103),1)
insert into DataDiff values (234,4,convert(datetime,'29/12/1998',103),0)
insert into DataDiff values (234,5,convert(datetime,'01/02/1999',103),1)
insert into DataDiff values (234,6,convert(datetime,'03/02/1999',103),0)
insert into DataDiff values (234,7,convert(datetime,'03/02/1999',103),1)
insert into DataDiff values (234,8,convert(datetime,'29/03/1999',103),0)
insert into DataDiff values (234,9,convert(datetime,'29/03/1999',103),1)
insert into DataDiff values (234,10,convert(datetime,'31/03/1999',103),0)

我很难在没有RBAR的情况下重写UDF来计算从ID = 1到ID = 2的天数,然后从ID = 3到ID = 4,依此类推,当COUNTABLE = 1时始终开始计数并在COUNTABLE = 0时停止,然后返回给定CLI的总和。

图中五个区间的天数为:

ID=2 - ID=1  = 204
ID=4 - ID=3  = 140
ID=6 - ID=5  = 2
ID=8 - ID=7  = 54
ID=10 -ID=9  = 2

从ID = 1和ID = 10之间的总共469天总共402个“可计数”天数

1 个答案:

答案 0 :(得分:3)

尝试:

select t1.cli ,
       sum(t1.countable  * 
           datediff(day, t1.[DATE], coalesce(t2.[DATE],getdate())) ) daycount
from DataDiff t1
left join DataDiff t2 on t1.cli = t2.cli and t1.id+1 = t2.id
group by t1.cli

(假设如果cli的最后记录日期是可数的,那么它应该计算到当前日期。)