我有两个表,contribution(Member_number,Salyear,Salmonth,ReceiptDate)
和contribution_update(Member_number,Salyear,Salmonth,ReceiptDate)
。表Receiptdate
中的列contribution
具有空值。我想通过比较Member_Number
,Salyear
,Salmonth
的组合以及发生匹配的地方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;
该查询应该合并目标表中的许多行。
答案 0 :(得分:0)
您不需要WHERE
的{{1}}部分的UPDATE
条件,它由MERGE
条件处理。 ON
语句仅对匹配的行执行-因此,源和目标之间WHEN MATCHED
,MEMBER_NUMBER
和SALYEAR
相同的行。
让我们假设来源-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