获取SQL Server中每个组中的顶级ID

时间:2015-10-14 07:55:33

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2

我想添加一个包含每个组中第一个列的列。

样品:

Product       ID
Orange        1
Orange        2
Orange        3
Orange        4
Apple         5
Apple         6
Apple         7
Grapes        8
Grapes        9

期望的输出:

Product       ID
Orange        1
Orange        1
Orange        1
Orange        1
Apple         5
Apple         5
Apple         5
Grapes        8
Grapes        8

2 个答案:

答案 0 :(得分:1)

您可以使用MIN(ID) OVER (PARTITION BY Product)

SELECT Product, 
       ID = MIN(ID) OVER (PARTITION BY Product)
FROM dbo.Products
ORDER BY ID

Demo

今天的文章:Understanding the OVER clause

答案 1 :(得分:0)

我觉得蒂姆正确! 其他情况,你可以使用: SELECT P.Product FROM dbo.Products P CROSS APPLY (SELECT TOP 1 ID FROM dbo.Products WHERE Product = P.Product ORDER BY ID)