下面的代码是您的示例数据的完整工作示例,这里有一些有用的链接:
来自列值的 T-SQL CSV
递归 CTE
SET NOCOUNT ON
GO
DECLARE @RoomDays TABLE
(
[RoomID] INT NOT NULL
,[DateOf] DATE NOT NULL
,[Segment] CHAR(1) NOT NULL
)
INSERT INTO @RoomDays ([RoomID], [DateOf], [Segment] )
VALUES ('1','2013-07-03','1')
,('1','2013-07-04','1')
,('1','2013-07-05','6')
,('1','2013-07-15','6')
,('1','2013-07-16','6')
,('2','2013-07-08','1')
,('2','2013-07-09','1')
,('2','2013-07-10','6')
,('2','2013-07-11','6')
,('2','2013-07-12','1')
,('2','2013-07-13','1')
,('3','2013-07-19','6')
;WITH DataSource ([RoomID], [DateOf], [Segment], [Level]) AS
(
SELECT [RoomID], [DateOf], [Segment], 0 AS [Level]
FROM @RoomDays AS RD
UNION ALL
SELECT RD1.[RoomID], RD1.[DateOf], RD1.[Segment], [Level] + 1
FROM @RoomDays AS RD1
INNER JOIN DataSource DS
ON RD1.RoomID = DS.RoomID
WHERE DATEADD (DAY , 1 , DS.DateOf) = RD1.DateOf
),
StartDates AS
(
-- Retriving the "Start" records
SELECT [RoomID], [DateOf], [Segment]
FROM DataSource
WHERE [Level] = 0
EXCEPT
SELECT [RoomID], [DateOf], [Segment]
FROM DataSource
WHERE [Level] = 1
),
TempResult AS
(
-- Mathing each "Start" record with its values
SELECT SD.[DateOf] AS [StartDate]
,RD.[RoomId]
,RD.[DateOf]
,RD.[Segment]
FROM StartDates SD
INNER JOIN @RoomDays RD
ON SD.RoomID = RD.RoomID
AND SD.DateOf <= RD.DateOf
AND NOT EXISTS (SELECT 1 FROM StartDates WHERE DateOf <= RD.DateOf AND RoomID = RD.RoomID AND SD.DateOf < DateOf)
)
SELECT TR.[RoomID] AS [RoomID]
,MIN(TR.[DateOf]) AS [DateFrom]
,MAX(TR.[DateOf]) AS [DateThru]
,SUBSTRING((SELECT ',' + [Segment] FROM TempResult WHERE [StartDate] = TR.[StartDate] FOR XML PATH('')),2,4000) AS CSV
,COUNT(TR.[DateOf]) AS [NumDays]
FROM TempResult TR
GROUP BY TR.[RoomID],TR.[StartDate]
SET NOCOUNT OFF
GO
输出:
1 2013-07-03 2013-07-05 1,1,6 3
1 2013-07-15 2013-07-16 6,6 2
2 2013-07-08 2013-07-13 1,1,6,6,1,1 6
3 2013-07-19 2013-07-19 6 1
请注意,上面的代码可以放入视图或函数中,或者您可以“剪切”它并将每个 CTE 的结果保存在临时表或表变量表中。