29

我知道一些基本的 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

不幸的是,应用层要求基表采用所示格式。这可以在查询中执行吗?

4

5 回答 5

34
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

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

于 2011-04-14T11:36:06.380 回答
15
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少用一个会产生更好的执行计划。

于 2011-04-14T13:46:30.530 回答
0
SELECT MIN(Date) AS DateFrom,MAX(Date) AS DateTo, Crew, DayType FROM yourTableName GROUP BY Crew, DayType
于 2011-04-14T11:35:40.500 回答
-1

就像是:

SELECT Crew, DayType, MIN(Date) AS SomeDate1, MAX(Date) AS SomeDate2 
FROM Mytable 
GROUP BY Crew, DayType
于 2011-04-14T11:34:03.930 回答
-2
Select Min(Date) DateFrom, Max(Date) DateTo, Crew Name,DayType From Mytable Group By Crew,DayType 

尝试这个。

于 2011-04-14T11:40:31.580 回答