2012-12-05 94 views
4

我試圖合併兩個表,我想用GROUP BY爲了解決以下錯誤:如何在SQL MERGE語句中使用GROUP BY子句?

The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.

究竟會在哪裏GROUP BY子句中去?

MERGE dbo.MyTarget targ 
USING dbo.MySource src 
ON (targ.Identifier = src.Identifier 
    AND targ.Name = src.ConstituentName 
    AND targ.Ticker = src.ConstituentTicker 
    AND (targ.CUSIP = src.CUSIP OR targ.ISIN = src.ISIN OR targ.SEDOL = src.SEDOL)) 
WHEN MATCHED THEN 
-- update values 
; 
+0

(回滾爲[標籤:合併]不是有關SQL命令) – AakashM

回答

5

像這樣:

MERGE dbo.MyTarget targ 
USING (SELECT ... FROM dbo.MySource GROUP BY .....) src 
ON (targ.Identifier = src.Identifier 
    AND targ.Name = src.ConstituentName 
    AND targ.Ticker = src.ConstituentTicker 
    AND (targ.CUSIP = src.CUSIP OR targ.ISIN = src.ISIN OR targ.SEDOL = src.SEDOL)) 
WHEN MATCHED THEN 
-- update values 
;