我有一个包含日期和数字列的表,如下所示:
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
答案 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
答案 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