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)