如何查询具有日期的表,以便输出处于此特定的汇总形式?

时间:2018-04-09 11:15:17

标签: sql sql-server tsql

我正在使用SQL Server 2012,我的StayDateInfo数据库中有以下表(称为SQL Server)。该表包含大约200万条记录。

ResaID   StayDate    RoomCat
 100     2018-03-01    STD
 100     2018-03-02    STD
 150     2018-04-10    STD
 150     2018-04-11    STD
 150     2018-04-12    STD
 150     2018-04-13    DLX

我需要我的T-Sql查询来提供以下输出:

 ResaID   RoomCat    StartDate    EndDate      Length
 100      STD        2018-03-01   2018-03-02      2
 150      STD        2018-04-10   2018-04-12      3
 150      DLX        2018-04-13   2018-04-13      1

Length列基本上是StartDateEndDate之间的天数。

如何编写T-SQl查询来实现此输出?

3 个答案:

答案 0 :(得分:2)

使用group by子句

select ResaID, RoomCat,
       min(StayDate) as StartDate,
       max(StayDate) as EndDate,
       datediff(day, min(StayDate), max(StayDate))+1 as Length
from StayDateInfo s
group by ResaID, RoomCat

答案 1 :(得分:0)

以下查询有效

segmented

答案 2 :(得分:0)

您确实需要通过两列唯一的标识汇总每行来获取开始结束日期。 要获得长度,只需从两个日期获得DATEDIFF

CREATE TABLE [dbo].[StayDateInfo]
(
    ResaID int not null
   ,StayDate date not null
   ,RoomCat char(3) not null
)

GO

insert into [dbo].[StayDateInfo]
(ResaID, StayDate, RoomCat)
values
 (100,     '2018-03-01',    'STD')
,(100,     '2018-03-02',    'STD')
,(150,     '2018-04-10',    'STD')
,(150,     '2018-04-11',    'STD')
,(150,     '2018-04-12',    'STD')
,(150,     '2018-04-13',    'DLX')
GO

select * from [dbo].[StayDateInfo]

select sdi.ResaID, sdi.RoomCat
      , min(sdi.StayDate) as [StartDate]
      , max(sdi.StayDate) as [EndDate]
      , DATEDIFF(DAY, min(sdi.StayDate), max(sdi.StayDate)) + 1 as [Length]
from [dbo].[StayDateInfo] sdi
group by sdi.ResaID, sdi.RoomCat

输出正是您所要求的。