开发者

Aggregating dates in SQL Server

开发者 https://www.devze.com 2023-03-10 05:46 出处:网络
I have a 2-column table named Assignment. The table contains assignment of Person (nvarchar(20)) and Day (date), like here:

I have a 2-column table named Assignment. The table contains assignment of Person (nvarchar(20)) and Day (date), like here:

Person      Day
------------------
John    2011-05-23
John    2011-05-24
John    2011-05-25
John    2011-05-27
John    20开发者_Go百科11-05-28
John    2011-05-29
Anna    2011-05-02
Anna    2011-05-03
Anna    2011-05-06

I need to extract the date ranges when there is a sequence of adjacent days. The output should be a single string value for every row:

------------------
John    2011-05-23 - 2011-05-25
John    2011-05-27 - 2011-05-29
Anna    2011-05-02 - 2011-05-03
Anna    2011-05-06 - 2011-05-06

I tried grouping and then

   CAST(min(Day) AS VARCHAR) + ' - ' + CAST(max(Day) AS VARCHAR)

but it does not work correctly.

Any advice is welcome. Thanks.


declare @T table(Person nvarchar(20), [Day] date)

insert into @T values
('John',    '2011-05-23'),
('John',    '2011-05-24'),
('John',    '2011-05-25'),
('John',    '2011-05-27'),
('John',    '2011-05-28'),
('John',    '2011-05-29'),
('Anna',    '2011-05-02'),
('Anna',    '2011-05-03'),
('Anna',    '2011-05-06')


;WITH cte AS
(
SELECT *,
        DATEDIFF(DAY,0,[Day])-
        ROW_NUMBER() OVER (PARTITION BY Person ORDER BY [Day]) AS Grp
FROM @T  
)
SELECT Person, 
       MIN([Day]) AS DateFrom, 
       MAX([Day]) AS DateTo  
FROM cte 
GROUP BY Person, Grp
0

精彩评论

暂无评论...
验证码 换一张
取 消