sql - 使用同一表中的另一组记录更新表中某些行的列
问题描述
我有一张表(银行),上面有这样的记录——
BRANCH | CITY | STATE | ZIP
-----------------------------------------------
Corporate | City1 | State1 | Zip1
Corporate | City2 | State2 | Zip2
Corporate | City3 | State3 | Zip3
Corporate | City4 | State4 | Zip4
Corporate | City5 | State5 | Zip5
Corporate | City6 | State6 | Zip6
1 | City1 | State1 |
1 | City4 | State4 | Zip4
1 | City6 | State6 | Zip2
1 | City10 | State10 | Zip10
2 | City1 | State1 | Zip1
2 | City2 | State2 | Zip2
2 | City3 | State3 | Zip3
2 | City5 | State5 | Zip4
需要通过匹配 'City' 和 'State' 使用 Branch 'Corporate' 更新 Branch '1' 的 ZIP 列。它不应更新分支 1 的记录 City10,即 Zip 应保持 Zip10。最后结果 -
BRANCH | CITY | STATE | ZIP
-----------------------------------------------
Corporate | City1 | State1 | Zip1
Corporate | City2 | State2 | Zip2
Corporate | City3 | State3 | Zip3
Corporate | City4 | State4 | Zip4
Corporate | City5 | State5 | Zip5
Corporate | City6 | State6 | Zip6
1 | City1 | State1 | Zip1
1 | City4 | State4 | Zip4
1 | City6 | State6 | Zip6
1 | City10 | State10 | Zip10
2 | City1 | State1 | Zip1
2 | City2 | State2 | Zip2
2 | City3 | State3 | Zip3
2 | City5 | State5 | Zip4
我使用了以下 SQL,但它正在更新 Branch 1 的记录,其中未找到 Corporate 的 City 和 State 匹配项。
Update Bank T1
set T1.zip = (select max(T2.zip) from Bank T2 where T1.city = T2.city and T1.state = T2.state and T2.branch ='Corporate' )
where T1.branch = '1'
解决方案
您可以使用显式join
:
update Bank b
set b.zip = b2.zip
from Bank b join
(select city, state, max(b2.zip) as zip
from Bank b2
where b2.branch = 'Corporate'
group by city, state
) b2
on b2.city = b.city and b2.state = b.state and
where b.branch = '1';
您也可以使用您的方法,但您需要考虑不匹配的值:
update Bank
set b.zip = (select coalesce(max(b2.zip), bank.zip)
from Bank b2
where b2.city = bank.city and b2.state = bank.state and b2.branch = 'Corporate'
)
where branch = '1';
但是,这将不必要地更新值不变的行。
推荐阅读
- php - 在子包中构建 laravel 就绪的 ORM 模型?(什么依赖?)
- python - pca-valueError:无法将字符串转换为浮点数:'finalized'
- android - 我想为片段编写一个通知按钮,但我的代码有一些问题
- python - 使用 twinx() 时 X 轴日期范围发生变化
- c# - 如何从 ASP.NET MVC 5 中的不同控制器(站点范围)访问 cookie?
- angular - 在有角度的前端应用程序上隐藏我的私钥 RSA
- elasticsearch - 多行日志的顺序不正确
- rust - 在 Rust 中使用泛型、特征别名和构造函数
- azure-devops - 如果我是发起该部署的人,则自动授予我对发布的批准
- apache-nifi - 如何监控 NIFI 流文件存储和内容存储阈值