增量"序列"列基于另一列的字母顺序

时间:2014-12-19 09:47:29

标签: sql sql-server select row-number

假设以下架构:

text|sequence
----|--------
Foo |       1
Bar |       2
Baz |       3

我如何UPDATE sequence列,从1开始递增,根据text列的字母顺序没有间隙?

结果数据如下所示:

text|sequence
----|--------
Foo |       3
Bar |       1
Baz |       2

2 个答案:

答案 0 :(得分:2)

试试这个:

UPDATE A 
SET A.sequene = B.sequence 
FROM tableA A 
INNER JOIN (SELECT text, ROW_NUMBER() OVER (ORDER BY text) sequence 
            FROM tableA 
           ) AS B ON A.text = B.text

答案 1 :(得分:0)

试试这个

UPDATE A
SET A.Sequence = A.newSequence
FROM (SELECT Text, Sequence, ROW_NUMBER() OVER (ORDER BY sequence) newSequence
            FROM TABLEA) A