如何在合并或更新操作期间比较源表和目标表之间的三个列

时间:2019-04-05 08:57:06

标签: sql

我有两个表,contribution(Member_number,Salyear,Salmonth,ReceiptDate)contribution_update(Member_number,Salyear,Salmonth,ReceiptDate)。表Receiptdate中的列contribution具有空值。我想通过比较Member_NumberSalyearSalmonth的组合以及发生匹配的地方Receiptdate进行更新来更新该列。

我编写了以下代码,但它合并了o值。

对如何改进或重写脚本有想法的人。

我从此代码开始

MERGE INTO CONTRIBUTION cgt
USING (select MEMBER_NUMBER,SALYEAR,SALMONTH,RECEIVED_DATE from CONTRIBUTION_UPDATE  )cga
ON (cgt.MEMBER_NUMBER=cga.MEMBER_NUMBER AND cgt.SALYEAR=cga.SALYEAR AND cgt.SALMONTH=cga.SALMONTH)
WHEN matched then
update 
SET cgt.RECEIPTDATE=cga.RECEIVED_DATE;

然后我发现表contribution_update具有重复项(Gor消息无法获得稳定的行集。。)。我重新创建了表,其中没有重复项。

MERGE INTO Contribution M
      USING
      (Select Member_Number,Salyear,Salmonth,ReceiptDate From
(select MEMBER_NUMBER,SALYEAR,SALMONTH,RECEIptDATE,row_number() over (partition by MEMBER_NUMBER,SALYEAR,SALMONTH
 order by null ) as qry from Contribution_update)where qry=1) vu
              ON  (Vu.Member_Number = M.Member_Number and M.Salyear=Vu.Salyear and M.Salmonth=Vu.Salmonth )
  WHEN MATCHED
  THEN
  UPDATE
  SET  M.Receiptdate = Vu.ReceiptDate;
  WHERE M.Salyear=Vu.Salyear and M.Salmonth=Vu.Salmonth;

该查询应该合并目标表中的许多行。

1 个答案:

答案 0 :(得分:0)

您不需要WHERE的{​​{1}}部分的UPDATE条件,它由MERGE条件处理。 ON语句仅对匹配的行执行-因此,源和目标之间WHEN MATCHEDMEMBER_NUMBERSALYEAR相同的行。

让我们假设来源-SALMONTH像这样:

ContributionUpdate

目标-MEMBER_NUMBER SALYEAR SALMONTH RECEIVED_DATE ------------- ----------- ----------- ------------- 1 2019 1 2019-10-10 2 2019 1 2019-10-20 像这样:

Contribution

目标中有一个匹配行,对于成员1,2019年,第1个月。如果您只想使用源中的MEMBER_NUMBER SALYEAR SALMONTH RECEIVED_DATE ------------- ----------- ----------- ------------- 1 2019 1 NULL 更新匹配年,就足够了:

RECEIVED_DATE

如果您还想将源中缺少的一行插入到目标(对于成员2)中,则需要使用MERGE INTO Contribution t USING ContributionUpdate s ON s.MEMBER_NUMBER = t.MEMBER_NUMBER AND s.SALYEAR = t.SALYEAR AND s.SALMONTH = t.SALMONTH WHEN MATCHED THEN UPDATE SET RECEIVED_DATE = s.RECEIVED_DATE; (1 row affected) ,如下所示:

WHEN NOT MATCHED BY TARGET

结果,MERGE INTO Contribution t USING ContributionUpdate s ON s.MEMBER_NUMBER = t.MEMBER_NUMBER AND s.SALYEAR = t.SALYEAR AND s.SALMONTH = t.SALMONTH WHEN MATCHED THEN UPDATE SET RECEIVED_DATE = s.RECEIVED_DATE WHEN NOT MATCHED BY TARGET THEN INSERT ( MEMBER_NUMBER, SALYEAR , SALMONTH , RECEIVED_DATE ) VALUES ( s.MEMBER_NUMBER, s.SALYEAR , s.SALMONTH , s.RECEIVED_DATE ); (2 rows affected) 表将如下所示:

Contribution