Group By Date Range of Sequenced Only

混江龙づ霸主 提交于 2019-12-25 03:45:13

问题


I am trying to generate a date range sequence and put date in second row if sequencing is break.

fldDate        TotalNo
2015-04-01     10
2015-04-02     10
2015-04-03     10
2015-04-04     10
2015-04-05     10
2015-04-06     10
2015-04-07     10
2015-04-08     10
2015-04-09     12
2015-04-10     12
2015-04-11     12
2015-04-12     12
2015-04-20     12
2015-04-21     12
2015-04-22     12
2015-04-23     12
2015-04-24     12
2015-04-25     12

I am really stumped

I want this table as

StartDate      EndDate      TotalNo
2015-04-01     2015-04-08   10
2015-04-09     2015-04-12   12
2015-04-20     2015-04-25   12

Means Either date range breaks or TotalNo change It should create a new row.

I have done it but its not working completely I am doing like

SELECT MIN(fldDate) AS StartDate,
       MAX(fldDate) AS EndDate,
       TotalNo
FROM dbo.tbl1
GROUP BY TotalNo
ORDER BY fldDate

It will create like

StartDate      EndDate      TotalNo
2015-04-01     2015-04-08   10
2015-04-09     2015-04-25   12

回答1:


You can identify the groups by subtracting an integer sequence from the fldDate -- such as provided by row_number(). Consecutive dates will have the same value after the subtraction. The rest is just group by:

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


来源:https://stackoverflow.com/questions/29472414/group-by-date-range-of-sequenced-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!