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

时间:2023-02-03 23:06:08

I'm a SQL noob and I need syntax help on how do I use a SET command to assign the values of my SortOrder Column. The below code does not Update the table but it's how I would like it to look (all SortOrder values are set to 0). I could go through manually but looking for a quick alternative (the data set is a bit bigger).

我是一个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

Thanks for the help

谢谢您的帮助

2 个解决方案

#1


2  

You can benefit from cte like below, assuming you are using SQL Server and your original table has already a column like SortOrder:

您可以从下面的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

If there is no SortOrder column already existing, you can do:

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

ALTER TABLE DesignColours
ADD SortOrder int
GO

The regular usage of update statement is:

update语句的常规用法是:

UPDATE tablename
set columnName = yourvalue
where <yourrule>

Ref: https://www.w3schools.com/sql/sql_update.asp

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

#2


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

#1


2  

You can benefit from cte like below, assuming you are using SQL Server and your original table has already a column like SortOrder:

您可以从下面的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

If there is no SortOrder column already existing, you can do:

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

ALTER TABLE DesignColours
ADD SortOrder int
GO

The regular usage of update statement is:

update语句的常规用法是:

UPDATE tablename
set columnName = yourvalue
where <yourrule>

Ref: https://www.w3schools.com/sql/sql_update.asp

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

#2


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