How to renumber rows by groups

2019-08-20 03:33发布

I need to renumber rows by group (Class, Color, Type) sequences in column SeqNo from:

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

to:

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

How to do that, please?

1条回答
对你真心纯属浪费
2楼-- · 2019-08-20 04:29

You need to use DENSE_RANK() function to number your sequence and the CTE for the intermediary result set.

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

The output:

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
查看更多
登录 后发表回答