![](/img/trans.png)
[英]Update column in Oracle table with value from another table with duplicates
[英]update column table(table has duplicates) with values of another column table
我需要用另一個表的值更新表中的列(表有重復項)。 我嘗試了幾個代碼,但它給了我錯誤
錯誤:更新已取消:嘗試使用來自多個連接行的值更新目標行
這是我的代碼:
UPDATE SERGIU_BI_CCM_AGG_MTH t1
SET t1.CURRENT_SEC = foo.CURRENT_SEC
FROM (
SELECT t1a.sub_id, t1a.CURRENT_BRAND, t2.CURRENT_SEC, t2.from_date,
t2.to_date
FROM SERGIU_BI_CCM_AGG_MTH t1a
LEFT JOIN BI_CCM_BASE t2
ON t1a.sub_id = t2.sub_id and t1a.CURRENT_BRAND = t2.CURRENT_BRAND
)
foo
WHERE t1.sub_id = foo.sub_id and t1.CURRENT_BRAND = foo.CURRENT_BRAND
and t1.agg_mth between to_char(foo.from_date,'YYYYMM') and
to_char(foo.to_date-1,'YYYYMM');
誰能幫我?
我認為您可以使用以下兩種方式:
UPDATE SERGIU_BI_CCM_AGG_MTH t1
LEFT JOIN BI_CCM_BASE t2
ON t1.sub_id = t2.sub_id and t1.CURRENT_BRAND = t2.CURRENT_BRAND
SET t1.CURRENT_SEC = t2.CURRENT_SEC
WHERE t1.agg_mth between to_char(t2.from_date,'YYYYMM') and
to_char(t2.to_date-1,'YYYYMM');
UPDATE SERGIU_BI_CCM_AGG_MTH t1, BI_CCM_BASE t2
SET t1.CURRENT_SEC = t2.CURRENT_SEC
WHERE t1.sub_id = t2.sub_id and t1.CURRENT_BRAND = t2.CURRENT_BRAND
and t1.agg_mth between to_char(t2.from_date,'YYYYMM') and
to_char(t2.to_date-1,'YYYYMM');
希望這可以幫助::)
重復導致錯誤,讓我們使用row_number()
獲取每個sub_id
和CURRENT_BRAND
的唯一記錄。
試試下面的查詢
UPDATE SERGIU_BI_CCM_AGG_MTH t1
SET t1.CURRENT_SEC = foo.CURRENT_SEC
FROM (
SELECT t1a.sub_id
, t1a.CURRENT_BRAND
, t2.CURRENT_SEC
, t2.from_date
, t2.to_date
, row_number() over (partition by t1a.sub_id,CURRENT_BRAND order by from_date desc) as rn
FROM SERGIU_BI_CCM_AGG_MTH t1a
LEFT JOIN BI_CCM_BASE t2 ON t1a.sub_id = t2.sub_id
and t1a.CURRENT_BRAND = t2.CURRENT_BRAND
)foo
WHERE t1.sub_id = foo.sub_id
and t1.CURRENT_BRAND = foo.CURRENT_BRAND
and t1.agg_mth between to_char(foo.from_date,'YYYYMM') and to_char(foo.to_date-1,'YYYYMM');
and foo.rn = 1
您需要以下查詢。
UPDATE SERGIU_BI_CCM_AGG_MTH t1
SET t1.CURRENT_SEC = (SELECT t2.CURRENT_SEC
FROM SERGIU_BI_CCM_AGG_MTH t1a
LEFT JOIN BI_CCM_BASE t2
ON t1a.sub_id = t2.sub_id and t1a.CURRENT_BRAND = t2.CURRENT_BRAND
WHERE t1.sub_id = foo.sub_id and t1.CURRENT_BRAND = foo.CURRENT_BRAND
and t1.agg_mth between to_char(foo.from_date,'YYYYMM') and
to_char(foo.to_date-1,'YYYYMM'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.