我必须找出至少连续3天出现价值的时期。
表格如下:
Dates val
--------------------
2002-10-25 0:00 37.8
2002-11-03 0:00 38.4
2002-11-04 0:00 37.2
2002-11-05 0:00 39.1
2002-11-15 0:00 38.6
2002-11-16 0:00 39
2002-11-18 0:00 38.3
2002-11-19 0:00 38.7
2002-11-20 0:00 39.7
2002-11-21 0:00 39.2
2002-11-22 0:00 39.6
2002-11-23 0:00 38.5
2002-11-28 0:00 37.5
2003-10-03 0:00 37.1
2003-10-06 0:00 38.1
2003-10-07 0:00 37.6
预期输出
Daterange NoOfDays
---------------------------------------------
2002-11-03 0:00-2002-11-05 0:00 3
2002-11-18 0:00-2002-11-23 0:00 6
答案 0 :(得分:3)
您可以通过为日期分配分组ID来执行此计算。一种简单的方法是减去一系列数字 - 差异对于一系列天数是不变的。然后按这个数字汇总:
select min(daterange), max(daterange), count(*) as numdays
from (select t.*,
dateadd(day,
- row_number() over (order by daterange),
daterange) as grp
from t
) t
group by grp
having count(*) >= 3;