分组连续的日期范围

时间:2014-12-10 15:12:28

标签: sql-server sql-server-2008 tsql sql-server-2012

我有一张包含此数据的表格(CurrentDay可用性价格MinStay IdRate):

2014-12-01  0   0.00    0   123456
2014-12-02  0   0.00    0   123456
2014-12-03  0   0.00    0   123456
2014-12-04  0   0.00    0   123456
2014-12-05  0   0.00    0   123456
2014-12-06  2   124.00  0   123456
2014-12-07  2   124.00  0   123456
2014-12-08  0   0.00    0   123456
2014-12-09  0   0.00    0   123456
2014-12-10  0   0.00    0   123456
2014-12-11  0   0.00    0   123456
2014-12-12  0   0.00    0   123456
2014-12-13  0   0.00    0   123456

可以创建一个查询(没有存储过程)来检索这样的结果吗?

2014-12-01 2014-12-05 0 0.00    0   123456
2014-12-06 2014-12-07 2 124.00  0   123456
2014-12-08 2014-12-13 0 0.00    0   123456

我试过这个但是错了

SELECT Min([CurrentDay])
      ,Max([CurrentDay])
      ,[Availability]
      ,[Price]
      ,[MinStay]
      ,[IdRate]
  FROM [ChannelBooking].[dbo].[Inventory]
  GROUP BY Price, MinStay, [IdRate], [Availability]

数据库是SQL Server 2008,实际上我是通过软件来完成的。

1 个答案:

答案 0 :(得分:0)

好吧也许我找到了解决方案:

 WITH    q AS
            (
            SELECT  [Availability], [Price],CurrentDay,
                    ROW_NUMBER() OVER (PARTITION BY [Availability], [Price] ORDER BY CurrentDay) AS rnd,
                    ROW_NUMBER() OVER (PARTITION BY [Availability] ORDER BY CurrentDay) AS rn,
                    ROW_NUMBER() OVER (ORDER BY CurrentDay) AS colID
            FROM    [Inventory]

            WHERE (CurrentDay >= '12-01-2014' and CurrentDay <= '12-31-2014')

            )
    SELECT  MIN(CurrentDay), MAX(CurrentDay), [Availability], [Price]
    FROM    q
    GROUP BY  [Availability], [Price], rnd - rn, rnd - colID
    ORDER BY      MIN(CurrentDay)