获取SQL服务器中每个组的top ID

Get the top ID in each group in SQL Server

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

样本:

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

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

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

Demo

今天的文章:了解 OVER 子句

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