简体   繁体   English

SQL 脚本根据其他列值更新列值

[英]SQL script to update column values based on other column values

I am new to writing SQL scripts and I am using SQL Server.我是编写 SQL 脚本的新手,我正在使用 SQL 服务器。

I have a table of data:我有一个数据表:

在此处输入图像描述

As you can see some of the race_title_short values are NULL.如您所见, race_title_short的一些值是 NULL。 I want to update the values in this column based on the race_identifier_code .我想根据race_identifier_code更新此列中的值。

For example one of the race_identifier codes is CORL which has a race_title_short of Coral Cup.例如其中一个race_identifier代码是CORL,它的race_title_short是Coral Cup。

One of the records has the race identified as CORL but has no race_title_short .其中一条记录将比赛标识为 CORL,但没有race_title_short

How do I update the NULL race_title_short based on the race_identifier_code which have race title shorts in?如何根据包含比赛标题短裤的race_identifier_code更新 NULL race_title_short

You can use a correlated subquery:您可以使用相关子查询:

update t
    set race_title_short = (select max(t2.race_title_short)
                            from t t2
                            where t2.race_identifier_code = t.race_identifier_code
                           )
    where race_title_short is null;

With a self join:自加入:

update t
set t.race_title_short = tt.race_title_short
from tablename t inner join tablename tt
on tt.race_identifier_code = t.race_identifier_code
where t.race_title_short is null and tt.race_title_short is not null

update t1 set t1.race_title_short = (select distinct race_title_short from test t2 where t2.race_identifier_code = t1.race_identifier_code and t2.race_title_short is not null) from test t1更新 t1 set t1.race_title_short = (select distinct race_title_short from test t2 where t2.race_identifier_code = t1.race_identifier_code and t2.race_title_short is not null) from test t1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM