我知道一些基本的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
不幸的是,应用层需要基表格格式为show。这可以在查询中做到吗?
谢谢
路
答案 0 :(得分:27)
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
您可能会对此文章感兴趣:
答案 1 :(得分:12)
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的解决方案相同,但使用一个ROW_NUMBER
更少会产生更好的执行计划。
答案 2 :(得分:0)
SELECT MIN(Date) AS DateFrom,MAX(Date) AS DateTo, Crew, DayType FROM yourTableName GROUP BY Crew, DayType
答案 3 :(得分:-1)
喜欢的东西:
SELECT Crew, DayType, MIN(Date) AS SomeDate1, MAX(Date) AS SomeDate2
FROM Mytable
GROUP BY Crew, DayType
答案 4 :(得分:-2)
Select Min(Date) DateFrom, Max(Date) DateTo, Crew Name,DayType From Mytable Group By Crew,DayType
试试这个。