按日期分组仅按顺序排列

时间:2015-04-06 13:39:17

标签: sql sql-server group-by date-range

我正在尝试生成日期范围序列,如果排序中断,则将日期放在第二行。

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

我真的很难过

我希望这个表格为

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

表示日期范围中断或TotalNo更改它应该创建一个新行。

我已经做到了,但它没有完全发挥作用 我喜欢

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

它会像

一样创建
StartDate      EndDate      TotalNo
2015-04-01     2015-04-08   10
2015-04-09     2015-04-25   12

1 个答案:

答案 0 :(得分:1)

您可以通过从fldDate中减去整数序列来识别组 - 例如row_number()提供的。减法后,连续日期将具有相同的值。其余的只是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;