SQL Server按日期排序然后组,但可能重复组

时间:2014-05-02 04:47:21

标签: sql sql-server

我在SQL Server表中有以下数据

Date         Crew
==================
'2010-07-01',Crew1
'2010-07-02',Crew2
'2010-07-03',Crew2
'2010-07-04',Crew2
'2010-07-05',Crew1
'2010-07-06',Crew1
'2010-07-07',Crew1
'2010-07-08',Crew1

我想如何提取数据

Date         Crew
==================
'2010-07-01',Crew1
'2010-07-02',Crew2
'2010-07-05',Crew1

即按日期排序,然后按工作人员分组并显示最小值(日期),但请注意重复的Crew1

到目前为止,我所能达到的只是

Date         Crew
==================
'2010-07-01',Crew1
'2010-07-02',Crew2

我如何实现我想要的?当我尝试按工作人员分组并按日期排序时,它不会让我!

4 个答案:

答案 0 :(得分:2)

如果您需要日期< 2014-07-31使用

的数据
 SELECT date, crew
   FROM table1
  WHERE date < '2010-07-31'
  GROUP BY date, crew
  ORDER BY date desc

否则请转到以下查询。它会根据您的需要对数据进行排序。

 SELECT date, crew
   FROM table1
  GROUP BY date, crew
  ORDER BY date desc

fiddle

答案 1 :(得分:0)

如果我正确理解您的问题,您需要在表格中记录2个最短日期。请检查下面的解决方案。

如果不符合您的要求,请发表评论

--Simulated your table
DECLARE @tbl TABLE
(
    [DATE] DATETIME,
    CREW VARCHAR(50)
)

--Inserted values for testing
INSERT INTO @tbl([DATE], CREW) VALUES('2010-07-01','Crew1')
INSERT INTO @tbl([DATE], CREW) VALUES('2010-07-02','Crew2')
INSERT INTO @tbl([DATE], CREW) VALUES('2010-07-03','Crew2')
INSERT INTO @tbl([DATE], CREW) VALUES('2010-07-04','Crew2')
INSERT INTO @tbl([DATE], CREW) VALUES('2010-07-05','Crew1')
INSERT INTO @tbl([DATE], CREW) VALUES('2010-07-06','Crew1')
INSERT INTO @tbl([DATE], CREW) VALUES('2010-07-07','Crew1')
INSERT INTO @tbl([DATE], CREW) VALUES('2010-07-08','Crew1')


--Your required query   
;WITH MyCTE AS
(
    SELECT * FROM @tbl
    WHERE [DATE] IN (
        SELECT TOP 2 [DATE] FROM @tbl
        GROUP BY [DATE]
        ORDER BY [DATE] ASC
    )
    GROUP BY [DATE], CREW
)

SELECT * FROM MyCTE
UNION ALL
SELECT TOP 1 * FROM @tbl
WHERE CREW = 'Crew1'
AND [DATE] NOT IN
(
    SELECT [DATE] FROM MyCTE
)

希望这有帮助

答案 2 :(得分:0)

这应该做:

 SELECT date, crew
 FROM table1
 GROUP BY date, crew

答案 3 :(得分:0)

不是那么简单吗?

SELECT 
  MIN([DATE]) as [Date]
 ,CREW 
FROM Table 
GROUP BY CREW
ORDER BY Date ASC