SQL - 使用合并并计算匹配和不匹配的结果

时间:2017-01-30 09:30:56

标签: sql sql-server merge count

因此,如果我使用以下查询,我想知道已匹配了多少行

MERGE (targetTable) AS t 
USING (sourceTable) AS s
ON t.ID = s.ID
WHEN MATCHED THEN
  (some statements)
WHEN NOT MATCHED BY SOURCE THEN
  (some statements)
WHEN NOT MATCHED BY TARGET THEN
  (some statements)

所以我想知道

的计数
  • 匹配
  • 与来源不匹配
  • 与目标不匹配

我知道你可以计算输出,但如果我没记错,输出只会考虑插入,更新和删除。

1 个答案:

答案 0 :(得分:1)

你可以在合并之前运行这样的东西:

SELECT  SUM(CASE WHEN t.ID = s.ID THEN 1 ELSE 0 END) as [Matched],
        SUM(CASE WHEN s.ID IS NULL THEN 1 ELSE 0 END) as [NotMatchedByTarget],
        SUM(CASE WHEN t.ID IS NULL THEN 1 ELSE 0 END) as [NotMatchedBySource]
FROM targetTable AS t 
FULL OUTER JOIN sourceTable AS s
    ON t.ID = s.ID