【问题标题】:How do I use the GROUP BY clause in a SQL MERGE statement?如何在 SQL MERGE 语句中使用 GROUP BY 子句?
【发布时间】:2012-11-23 12:38:57
【问题描述】:

我正在尝试合并两个表,我想使用 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
;

【问题讨论】:

  • (回滚为merge 与 SQL 命令无关)

标签: sql tsql merge group-by


【解决方案1】:

类似这样的:

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
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    相关资源
    最近更新 更多