在表格中组合日期范围

时间:2015-06-17 08:13:16

标签: sql sql-server

我有下表

id  price    startdate   enddate         product

1   112      12/05/2015   12/05/2015    A
2   112      13/05/2015   13/05/2015    A
3   112      14/05/2015   14/05/2015    A
4   112      15/05/2015   15/05/2015    A
5   732      16/05/2015   16/05/2015    A
6   732      17/05/2015   17/05/2015    A
7   112      18/05/2015   18/05/2015    A
8   112      19/05/2015   19/05/2015    A
9   112      20/05/2015   20/05/2015    A

我需要得到以下结果

id  price    startdate   enddate       product
1   112      12/05/2015   15/05/2015    A
2   732      16/05/2015   17/05/2015    A
3   112      18/05/2015   20/05/2015    A

2 个答案:

答案 0 :(得分:1)

您可以将DATEDIFFROW_NUMBER()一起使用。像这样的东西

<强>查询

;WITH CTE as
(
SELECT DATEDIFF(day, 0, startdate) - ROW_NUMBER()OVER(partition by price order by startdate)  r,*
from prod
)
SELECT ROW_NUMBER()OVER(ORDER BY MIN(id) ASC) as id,price,product,MIN(startdate) startdate,MAX(enddate) enddate
FROM cte c1
GROUP BY price,product,r

<强>输出

id  price   product startdate   enddate
1   112 A   2015-05-12  2015-05-15
2   732 A   2015-05-16  2015-05-17
3   112 A   2015-05-18  2015-05-20

SQL Fiddle

答案 1 :(得分:0)

使用像这样的How do I group on continuous ranges这样的公用表表达式肯定可以满足您的要求,但您可能需要查看以下讨论: Date Range for set of same data