如何计算连续日期

时间:2013-07-01 18:37:36

标签: tsql count sequential

我在T-Sql中寻找一个查询来计算连续日期的数量,向后计划弹出相同的日期,从最近的日期开始,并在日期有间隙时停止。

这是数据的一个例子:

Name    village Population  Date
Rob     village1    432     01/07/2013
Rob     village2    432     30/06/2013
Rob     village3    432     29/06/2013
Rob     village3    432     28/06/2013
Rob     village3    432     27/06/2013
Rob     village3    430     26/06/2013
Rob     village3    430     25/06/2013
Rob     village3    430     24/06/2013
Rob     village3    430     23/06/2013
Rob     village3    425     22/06/2013
Rob     village3    422     21/06/2013
Rob     village3    422     20/06/2013
Rob     village3    411     19/06/2013
Harry   Village1    123     01/07/2013
Harry   Village2    123     30/06/2013
Harry   Village3    122     29/06/2013
Pat     Village1    123     01/07/2013
Pat     Village2    123     30/06/2013
Pat     Village3    123     29/06/2013
Pat     Village4    100     20/06/2013
Tom     Village1    123     01/07/2013
Tom     Village2    123     30/06/2013
Tom     Village3    123     29/06/2013
Tom     Village4    123     28/06/2013

我希望得到以下结果:

Rob 5
Harry 2
Pat 3
Tom 3

数据应该更复杂,但是会有1000行,每人100个,连续日期的流行组,但我只希望第一组连续日期具有相同的弹出,从最新的向下。 / p>

2 个答案:

答案 0 :(得分:1)

with dd as 
(
   select distinct * from table
);
    select name, max(count) + 1
    from 
    (
       select t1.name, t1.village, t1.pop, count(*) as count
       from dd t1 
       join dd t2 
         on t2.village = t1.village
        and t2.pop  = t1.pop 
        and t2.pop  = t1.pop 
        and t2.date = dateadd(day,-1,t1.date)
       group by t1.name, t1.village, t1.pop
    )  dates
    group by name 

答案 1 :(得分:1)

;with a as
(
select name, village, population, date, cast(date as datetime) + dense_rank() over(partition by Population, name order by date desc) grp
from <your table>
), b as
(
select name, village, population, date, dense_rank() over (partition by name order by grp desc) rk
from a
)
select name, count(distinct date) from b
where rk = 1
group by name