我想按天数分组(+或 - )并使用分钟日期

时间:2014-08-18 11:25:20

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

ID        Date          Count
1,        2014-05-01    1
1,        2014-05-04    1 
1,        2014-05-10    1
2,        2014-05-02    1
2,        2014-05-03    1
2,        2014-05-09    1

如果我要分组时间差+/- 5天,这将成为

ID        Date          Count
1,         2014-05-01    2
1,         2014-05-10    1
2,         2014-05-02    2
2,         2014-05-09    1

这在Sequel Server 2012中是否可行?任何指针都将非常感激。感谢

1 个答案:

答案 0 :(得分:0)

我认为你想在有五天的差距时开始一个新的小组。因此,如果您有(1,2014-05-07)的记录,那么1只有一个组。

如果是这样,以下内容将起作用:

select id, min(date), sum(count)
from (select t.*, sum(HasGap) over (partition by id order by date) as grpid
      from (select t.*,
                   (case when datediff(day,
                                       lag(date) over (partition by id order by date),
                                       date) < 5
                         then 0 else 1
                    end) as HasGap
            from table t
           ) t
     ) t
group by id, grpid;