我想添加一个包含每个组中第一个列的列。
样品:
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
答案 0 :(得分:1)
您可以使用MIN(ID) OVER (PARTITION BY Product)
:
SELECT Product,
ID = MIN(ID) OVER (PARTITION BY Product)
FROM dbo.Products
ORDER BY ID
答案 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)