在纯SQL中对行进行分组

时间:2012-10-04 11:00:15

标签: sql sql-server grouping

我有一个包含日期和数字列的表,如下所示:

date        Number 
1-1-2012    1
1-2-2012    1
1-3-2012    2
1-4-2012    1

我想创建一个SQL查询,将具有相同Number的行分组并获取最小日期。仅当值iof Number与上一行/下一行相同时,才会发生分组。所以,结果是

date        Number 
1-1-2012    1
1-3-2012    2
1-4-2012    1

Cheerz,Lordkain

2 个答案:

答案 0 :(得分:6)

试试这个:

WITH   CTE AS(
       SELECT * ,ROW_NUMBER() OVER (ORDER BY [DATE] ) - 
                 ROW_NUMBER() OVER (PARTITION BY NUMBER ORDER BY [DATE] ) AS ROW_NUM
       FROM TABLE1)
SELECT NUMBER,MIN(DATE) AS DATE
FROM   CTE
GROUP BY ROW_NUM,NUMBER
ORDER BY DATE


SQL fiddle demo

答案 1 :(得分:0)

SELECT Number, MIN(date)
FROM table
GROUP BY Number
ORDER BY Number

既然你的要求更具体一点,那怎么样?我自己没有检查过,但考虑到你的要求,可能会有所作为。

SELECT date, Number FROM (
SELECT Number, 
(SELECT MIN(date) FROM #table t2 WHERE t1.date <> t2.date AND t1.Number = t2.Number) AS date 
FROM table t1
) AS a
GROUP BY number, date