使用同一 table 中的另一组记录更新 table 中某些行的列

Update a column for some rows in a table using another set of records from the same table

我有一个 table(银行)有这样的记录 --

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' 使用分支 'Corporate' 更新分支“1”的 ZIP 列。它不应更新 Branch 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 的记录,其中找不到与公司匹配的城市和州。

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';

但是,这将不必要地更新值未更改的行。