如何根据字母排序顺序设置int值

时间:2018-04-03 18:28:05

标签: sql sql-server sql-update sql-order-by row-number

我是一个SQL菜鸟,我需要语法帮助,如何使用SET命令分配我的SortOrder列的值。下面的代码不会更新表格,但它是我希望它看起来的样子(所有SortOrder值都设置为0)。我可以手动完成但寻找快速替代方案(数据集有点大)。

Select ROW_NUMBER() OVER (ORDER BY Name ASC) AS SortOrder, Name
From DesignColours

SortOrder |Name
1          Beige
2          Black
3          Blue
4          Brown
5          Copper

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

您可以从下面的cte中受益,假设您使用的是SQL Server,并且您的原始表已经有一个像SortOrder这样的列:

;with cte (SortOrder, Name) as (
   Select ROW_NUMBER() OVER (ORDER BY Name ASC) AS SortOrder, Name
   From DesignColours
)
update d
set d.SortOrder = cte.SortOrder
from DesignColours d
inner join cte on d.Name = cte.Name

如果尚未存在SortOrder列,您可以执行以下操作:

ALTER TABLE DesignColours
ADD SortOrder int
GO

update语句的常规用法是:

UPDATE tablename
set columnName = yourvalue
where <yourrule>

参考:https://www.w3schools.com/sql/sql_update.asp

答案 1 :(得分:2)

update a
set a.SortOrder = b.SortOrder
from DesignColours a
join 
(Select ROW_NUMBER() OVER (ORDER BY Name ASC) AS SortOrder, Name
   From DesignColours)b
on a.Name = b.Name