簡體   English   中英

ORACLE SQL 的合並/更新查詢

[英]MERGE / UPDATE Query for ORACLE SQL DEVELOPER

我有兩個不同的表,table1 和 table2,如下所示

表格1

LA_ID 地址 城市 STATE
572 A1 C1 S1
300 A1 C1 S1
978 A1 C1 S1
082 A2 C2 S2
026 A2 C2 S2
093 A2 C2 S2

表2

LA_ID
572
572
300
300
978
978
978
978
082
082
082
026
026
093

我想更新 table2 LA_ID 看起來像

LA_ID
572
572
572
572
572
572
572
572
082
082
082
082
082
082

基本上將table2的LA_ID更新為table1的LA_ID,其中ADDRESS、CITY和state是相同的。

我試過這個

SET LA_ID = (SELECT new_LA_ID from (
(Select min(LA_ID) over
(partition by ADDRESS, city, state) as new_LA_ID,
LA_ID old_LA_ID
from table2 )) src
where src.old_LA_ID = tgt.LA_ID )
where tgt.LA_ID in (Select LA_ID old_LA_ID
from table2 
);





如果您願意只使用最小值或最大值,則可以簡單地使用update

update table_2 t2
    set la_id = (select min(t1.la_id)
                 from table_1 t1 join
                      table_1 t12
                      on t1.state = t12.state and t1.city = t12.city and t1.address = t12.address
                 where t12.la_id = t2.la_id
                )
    where la_id <> (select min(t1.la_id)
                    from table_1 t1 join
                         table_1 t12
                         on t1.state = t12.state and t1.city = t12.city and t1.address = t12.address
                    where t12.la_id = t2.la_id
                   );

我不確定在有重復項時如何為所需的特定 ID 選擇572082 這將選擇300026

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM