在SQL Server中重新排序一组数据

时间:2009-10-13 15:23:46

标签: sql sql-server tsql common-table-expression

我有一个像这样的值表:

CREATE TABLE 
(
    Name1 VARCHAR (50),
    Name2 VARCHAR (50),
    Sequence INT
)

在这张表中我有这样的行

'Bob', 'Jones', 1
'James','Ant', 2

我想要根据Name2列的顺序更新UPDATE(UPDATE SET)序列的最佳方法,因此当重新排序时,值为:

'James','Ant', 1
'Bob', 'Jones', 2

我很确定这可以通过CTE的ROW_NUMBER OVER()样式完成,但不确定确切的语法。

4 个答案:

答案 0 :(得分:6)

您可以更新CTE:

WITH OrderedT AS
(
  SELECT Sequence, 
  ROW_NUMBER() OVER (ORDER BY Name2, Name1) as rn
  FROM T
)
UPDATE OrderedT
SET Sequence = rn;

答案 1 :(得分:4)

这样的事情怎么样:

WITH OrderedByName AS
(
  SELECT Name1, Name2, 
  ROW_NUMBER() OVER(ORDER BY Name2, Name1) as 'RowNum'
  FROM YourTable
)
UPDATE YourTable
SET Sequence = obn.RowNum
FROM OrderedByName obn
WHERE obn.Name1 = YourTable.Name1 
  AND obn.Name2 = YourTable.Name2

马克

答案 2 :(得分:1)

您不需要使用CTE,派生表也可以使用,试试这个:

create table abc 
(
    Name1 VARCHAR (50),
    Name2 VARCHAR (50),
    Sequence INT
)

insert into abc values ('Bob', 'Jones', 1
)
insert into abc values ('James','Ant', 2
)

SELECT * FROM abc ORDER BY Sequence

UPDATE a
    SET Sequence=dt.Rank
    FROM abc a
        INNER JOIN (SELECT
                        Name1, Name2 
                            ,ROW_NUMBER() OVER(ORDER BY Name2, Name1,Sequence) AS Rank
                     FROM abc
                   ) dt ON a.Name1=dt.Name1 AND a.Name2=dt.Name2

SELECT * FROM abc ORDER BY Sequence

输出:

Name1               Name2    Sequence
------------------- -------- -----------
Bob                 Jones    1
James               Ant      2

(2 row(s) affected)

(2 row(s) affected)

Name1               Name2    Sequence
------------------- -------- -----------
James               Ant      1
Bob                 Jones    2

(2 row(s) affected)

答案 3 :(得分:0)

响应KM的解决方案 - 2005年以前的MS SQL不支持ROW_NUMBER()。