在SQL Server中聚合日期

时间:2011-06-02 20:55:21

标签: sql tsql sql-server-2008 date aggregate-functions

我有一个名为Assignment的2列表。该表包含Person(nvarchar(20))和Day(date)的分配,如下所示:

Person      Day
------------------
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

我需要在有一系列相邻日期时提取日期范围。输出应该是每行的单个字符串值:

------------------
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

我尝试了分组然后

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

但它无法正常工作。

欢迎任何建议。 感谢。

1 个答案:

答案 0 :(得分:3)

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