-1

我在 T-Sql 中寻找一个查询来计算连续日期的数量,在 pop 相同的地方向后计算,从最新的日期开始,当日期有间隙时停止。

这是一个数据示例:

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 行和具有连续日期的流行组,但我只想要从最新向下的具有相同流行的第一组连续日期。

4

2 回答 2

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 
于 2013-07-01T20:57:35.557 回答
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
于 2013-07-02T09:18:58.820 回答