我如何分组连续的范围

我知道一些基本的SQL,但是这个超越了我。 我看起来高低,但没有骰子。 我需要查看以下数据,我可以在应用程序层代码中执行此操作。 但不幸的是,对于这个特定的代码,代码必须放在数据层中。

我正在使用T-SQL。

Date Crew DayType 01-02-11 John Doe SEA 02-02-11 John Doe SEA 03-02-11 John Doe SEA 04-02-11 John Doe HOME 05-02-11 John Doe HOME 06-02-11 John Doe SEA 

我需要这样的看法

 DateFrom DateTo Name DayType 01-02-11 03-02-11 John Doe SEA 04-02-11 05-02-11 John Doe HOME 06-02-11 06-02-11 John Doe SEA 

不幸的是,基表是应用程序层需要格式显示所需的。 这是可能做的查询?

谢谢

卢克

 WITH q AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY crew, dayType ORDER BY [date]) AS rnd, ROW_NUMBER() OVER (PARTITION BY crew ORDER BY [date]) AS rn FROM mytable ) SELECT MIN([date]), MAX([date]), crew AS name, dayType FROM q GROUP BY crew, dayType, rnd - rn 

这篇文章可能会对你感兴趣:

  • SQL需要的东西:SERIES()
 WITH grouped AS ( SELECT *, grp = DATEDIFF(day, 0, Date) - ROW_NUMBER() OVER (PARTITION BY Crew, DayType ORDER BY Date) FROM @testtable ) SELECT DateFrom = MIN(Date), DateTo = MAX(Date), Name = Crew, DayType FROM grouped GROUP BY Crew, DayType, grp; 

基本上,与Quassnoi的解决scheme相同,但使用较less的ROW_NUMBER产生更好的执行计划。

 SELECT MIN(Date) AS DateFrom,MAX(Date) AS DateTo, Crew, DayType FROM yourTableName GROUP BY Crew, DayType 

就像是:

 SELECT Crew, DayType, MIN(Date) AS SomeDate1, MAX(Date) AS SomeDate2 FROM Mytable GROUP BY Crew, DayType 
 Select Min(Date) DateFrom, Max(Date) DateTo, Crew Name,DayType From Mytable Group By Crew,DayType 

尝试这个。