说我有2列
Product Product_Cat
------- -----------
Cat 0
Dog 0
Potatoes 2
Carrots 2
Laundry 1
Bird 0
我想在第三个身份列上添加,但我希望每个Product_Cat的编号都是唯一的所以输出看起来像
Product Product_Cat Cat_Ident
------- ----------- ---------
Cat 0 1
Dog 0 2
Potatoes 2 1
Carrots 2 2
Laundry 1 1
Bird 0 3
您如何做到这一点?
这当然不是我的真实数据,而是我想做的简化。在我的实时系统中,我有4585个不同的“ Product_Cat”值,并且类别中的范围从1到2408“ Products”。
您需要使用RANK()
,如下所示:
RANK()
结果是:
ID产品Product_Cat Cat_Ident----------- -------- ----------- -----------1猫0 12狗0 23土豆2 14胡萝卜2 25洗衣1 16鸟0 3(受影响的6行)
我们需要更多信息,但您似乎需要使用触发器来形成cat_ident的值。
简单的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
应该会帮助
SELECT COUNT()+1 GROUP BY ProductCat