使用另一列 table 的值更新列 table(table 有重复项)

update column table(table has duplicates) with values of another column table

我需要用另一个 table 的值更新 table(table 有重复项)中的列。我尝试了几个代码,但它给了我错误

ERROR: Update canceled: attempt to update a target row with values from multiple join rows

这是我的代码:

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

谁能帮帮我?

我认为您可以使用以下两种方式:

  • 和"join"

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');
  • 没有"join":
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_idCURRENT_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'))