如何为SQL Server中的重复列添加不同的值?

问题描述 投票:2回答:2

我有一张桌子有CountryNameid

例如。

id   CountryName 
-----------------
1    Afghanistan
2    Afghanistan
3    Afghanistan 
4    Albania     
5    Albania     
6    Albania     
7    Albania   

我想添加一个新的列CountryID,其中所有重复的CountryName将具有如下所示的明显CountryID

例如。

id   CountryName   CountryID
-----------------------------    
1    Afghanistan      1
2    Afghanistan      1
3    Afghanistan      1
4    Albania          2
5    Albania          2
6    Albania          2
7    Albania          2

我有很多国家不断重复,我想向他们添加一个CountryID,以便更容易进行连接。是否可以通过T-Sql脚本来完成?

sql-server ssms
2个回答
5
投票

也许使用DENSE_RANK()的另一种选择:

Select id 
      ,CountryName
      ,CountryID  = dense_rank() over (order by CountryName)
From   YourTable

1
投票

所以,我知道你想将这些CountryID添加到表中。 因此,您需要更新语句来更新列CountryID。

扩展John Cappelletti's answer关于使用Dence_Rank,我认为以下更新语句应该有效。

UPDATE t1 SET t1.CountryID = t2.CountryID
    FROM [Your table] t1
    JOIN (Select id 
          ,CountryName
          ,CountryID  = dense_rank() over (order by CountryName)
    From   [Your table]) t2 ON t1.CountryName = t2.CountryName
© www.soinside.com 2019 - 2024. All rights reserved.