SQL Server 在普通sql中对行进行分组

dm7nw8vv  于 2022-12-26  发布在  其他
关注(0)|答案(2)|浏览(123)

我有一个包含Date和Number列的Table,如下所示:

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

我想做一个sql查询,将具有相同Number的行分组,并取最小日期。只有当Number的值iof与上一行/下一行相同时,才会进行分组。因此,结果为

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

rsl1atfo1#

试试这个:

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小提琴演示

8ljdwjyq

8ljdwjyq2#

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

既然你的要求比较具体,这个怎么样?2我还没有亲自检查过,但是考虑到你的要求,我想做一些可能有用的事情。

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

相关问题