Sql Date Grouping with avaliable dates in database

后端 未结 3 437
野性不改
野性不改 2021-01-17 05:17
ID         dateandtime  EmailID
73  6/8/2014 00:00:00   2
74  6/9/2014 00:00:00   2
75  6/10/2014 00:00:00  2
76  6/11/2014 00:00:00  2
77  6/12/2014 00:00:00  2
78  6/13         


        
3条回答
  •  时光取名叫无心
    2021-01-17 05:48

    This is an example of identifying groups of things that occur in order. In this case, the groups are in order by date and you want consecutive dates.

    You can find the group by using the different in two sequential values. Enumerate the values by date. Then enumerate the values by date and emailId. The difference is a constant for sequential values with the same emailId. Here is how it would work in your case:

    select min(TheDate) as StartDate, max(TheDate) as EndDate, emailId
    from (select t.*,
                 dateadd(day, - row_number() over (order by TheDate), theDate) as grp
          from table t
         ) t
    group by grp, emailId;
    

提交回复
热议问题