gpt4 book ai didi

SQL Server : update rows based other rows in the same table

转载 作者:行者123 更新时间:2023-12-02 09:32:29 24 4
gpt4 key购买 nike

我在我的项目中使用 SQL Server,我必须根据同一个表中的其他行更新某些行的列值。这是我的表:

| Name | Code | Locale
--------------------
| A | ab | en
| A | cd | ar
| A | ef | ru
| B | gh | ar

我需要根据区域设置为“en”且名称中具有相同值的行的代码值更新区域设置不是“en”的行的代码值。保证在 Locale 中带有“en”的每一行在 Name 中都有一个唯一的值。所以这就是我希望实现的目标
| Name | Code | Locale
--------------------
| A | ab | en
| A | ab | ar
| A | ab | ru
| B | gh | ar

我在 SO Update row with data from another row in the same table 找到了这个帖子,并尝试了以下方法,但都没有奏效。
UPDATE mytable dt1, mytable dt2 
SET dt1.code = dt2.code
WHERE dt1.NAME = dt2.NAME
AND dt1.code <> 'en'
AND dt2.code = 'en'

UPDATE mytable t1
INNER JOIN mytable t2 ON t1.NAME = t2.NAME and t2.code = 'en'
SET t1.code = t2.code;
WHERE t1.code <> 'en'

最佳答案

在 SQL Server 中,您可以使用 join 来做到这一点。在 update .正确的语法是:

update t
set code = teng.code
from mytable t join
(select t2.*
from mytable t2
where t2.locale = 'en'
) teng
on teng.name = t.name;

实际上,子查询并不是真正必要的:
update t
set code = teng.code
from mytable t join
mytable teng
on teng.name = t.name and teng.locale = 'en'

关于SQL Server : update rows based other rows in the same table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31408509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com