0

我想添加一个包含每个组中第一个的列。获取SQL Server中每个组中的顶级ID

样品:

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

Apple:5,5,7? ,有点混乱。 – Japongskie

+0

'MIN(ID)OVER(PARTITION BY Product)'会做到这一点。 [SQL小提琴](http://sqlfiddle.com/#!6/9eecb7/3867/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

+0

Yeyyy!谢谢!得到它了! :) – ohhzumm

0

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