如何更新 SQL 服务器中的顺序?

How to update with order in SQL Server?

我正在使用 SQL 服务器,我的 table 看起来像这样:

i    id   distance
-----------------
41   null    24
49   null    58
38   null    58
48   null    83
95   null    95
44   null    95
23   null    95

我想更新 id 以具有按 distance asc 排序的行序列,然后 i asc

我试过了

update mytable
set @id = @id + 1
id = @id
order by distance, i

但我遇到了错误

Incorrect syntax near "order"

如何解决?

您需要在派生的 table 或 CTE 中使用 ROW_NUMBER

例如如下

UPDATE T
SET    id = RN
FROM   (SELECT id,
               RN = ROW_NUMBER() OVER ( ORDER BY distance, i)
        FROM   mytable)T