在SQL中按日期差异分组

时间:2018-09-12 16:30:40

标签: sql sql-server sql-server-2012

我正在使用SQL Server 2012,似乎无法弄清楚如何使用数字序列填充“ episode”列,其中仅在date(“ start_date”,“ end_date”)处增加1差异大于30天。

任何帮助将不胜感激。

sample

1 个答案:

答案 0 :(得分:2)

您可以使用lag()和累计金额。但是,您已经完成了lag(),所以:

select t.*,
       sum(case when date_delta > 30 then 1 else 0 end) over (partition by id order by start_date) + 1 as episode
from t;

如果您还需要计算date_delta

select t.*,
       sum(case when start_date > dateadd(day, 30, prev_date)
                then 1 else 0
           end) over (partition by id order by start_date) + 1 as episode
from (select t.*,
             lag(start_date) over (partition by id order by start_date) as prev_date
      from t
     ) t;