English 中文(简体)
在SQL Server中聚合日期
原标题:Aggregating dates in SQL Server

我有一个名为Assignment的两列表。该表包含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)

但是它不能正确地工作。

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
问题回答

暂无回答




相关问题
Mysql compaire two dates from datetime?

I was try to measure what is faster and what should be the best way to compare two dates, from datetime record in MySql db. There are several approaches how to grab a date from date time, but I was ...

iPhone Date Picker rolls over to 2010 on December 27th?

So I implemented a UIDatepicker in one of my applications for scheduling and autodialing teleconferences... everything is pretty much ready to go except, while testing I noticed that when the date ...

Convert date Python

I have MMDDYY dates, i.e. today is 111609 How do I convert this to 11/16/2009, in Python?

specifying date format when using $form->inputs() in CakePHP

I am wondering if there is a way to specify the date format in the forms created using CakePHP s $form->inputs(); Please note that this is not the individual $form->input() but instead $form->inputs() ...

NSDateFormat, super simple! Where am I screwing up?

Ok, this is really simple, maybe I m a getting a bit burnt out, but seems like it should work, Query XML feed, put out date string, format, display in a cell. The issue is I m a getting a NULL ...

sqlite writing a date into an email

I am exporting a date value from sqlite and placing it into an email. The date appears like this 279498721.322872 I am using Objective C in an Iphone App. Does anyone know how to make this export ...

热门标签