Вам необходимо использовать RANK()
следующим образом:
CREATE TABLE #Products
(
ID int IDENTITY(1,1),
Product nvarchar(8),
Product_Cat int
)
GO
INSERT INTO #Products (Product, Product_Cat)
VALUES ('Cat', 0)
,('Dog', 0)
,('Potatoes', 2)
,('Carrots', 2)
,('Laundry', 1)
,('Bird', 0)
GO
ALTER TABLE #Products
ADD Cat_Ident int
GO
UPDATE #Products
SET Cat_Ident = rankVal
FROM #Products
INNER JOIN (
SELECT ID, RANK () OVER (PARTITION BY Product_Cat ORDER BY ID ) AS rankVal
FROM #Products ) rankings ON #Products.ID = rankings.ID
SELECT * FROM #Products
DROP TABLE #Products
Результат:
ID Product Product_Cat Cat_Ident
----------- -------- ----------- -----------
1 Cat 0 1
2 Dog 0 2
3 Potatoes 2 1
4 Carrots 2 2
5 Laundry 1 1
6 Bird 0 3
(6 row(s) affected)