如何按组重新编号行

时间:2014-08-26 10:05:36

标签: sql sql-server sql-server-2012 group-by sequence

我需要按照Class, Color, Type列中的组(SeqNo)序列重新编号行:

Class  | Color | Type | SeqNo
Animal | Brown | Terr | 1
Animal | Brown | Aqua | 3
Animal | White | Terr | 3
Plant  | Green | Aqua | 2
Plant  | Green | Aqua | 2
Plant  | Green | Aqua | 2
Platn  | Green | Terr | 9

为:

Class  | Color | Type | SeqNo
Animal | Brown | Terr | 1
Animal | Brown | Aqua | 2
Animal | White | Terr | 1
Plant  | Green | Aqua | 1
Plant  | Green | Aqua | 1
Plant  | Green | Aqua | 1
Plant  | Green | Terr | 2

请问怎么做?

1 个答案:

答案 0 :(得分:3)

您需要使用DENSE_RANK()函数对序列进行编号,并使用CTE作为中间结果集。

INSERT INTO @t VALUES
('Animal', 'Brown', 'Terr', 1),
('Animal', 'Brown', 'Aqua', 3),
('Animal', 'White', 'Terr', 3),
('Plant', 'Green', 'Aqua', 2),
('Plant', 'Green', 'Aqua', 2),
('Plant', 'Green', 'Aqua', 2),
('Plant', 'Green', 'Terr', 9)

;WITH cte AS(
SELECT *, DENSE_RANK() OVER (PARTITION BY Class, Color ORDER BY Class, Color, Type) AS NewSeq 
FROM @t 
) 
UPDATE t1
SET t1.SeqNo = t2.NewSeq
FROM @t AS t1
INNER JOIN cte AS t2 ON t1.Class = t2.Class AND t1.Color = t2.Color AND t1.Type = t2.Type

SELECT * FROM @t

输出:

Class   Color   Type    SeqNo
Animal  Brown   Terr    2
Animal  Brown   Aqua    1
Animal  White   Terr    1
Plant   Green   Aqua    1
Plant   Green   Aqua    1
Plant   Green   Aqua    1
Plant   Green   Terr    2