【问题标题】:T-SQL Merge when matched not working匹配时 T-SQL 合并不起作用
【发布时间】:2017-01-12 14:55:43
【问题描述】:

我有一个包含域之间电子邮件流量数据的临时表,如下所示:

[EmailId|SendingDomainId|SendingDomainName|RecipientDomainId|RecipientDomainName]

[500|600|abc.com|700|pqr.com]

[501|601|def.com|701|stu.com]

[501|601|def.com|700|pqr.com]

[502|600|abc.com|700|pqr.com]

即:

  • 电子邮件 ID 500 已从 abc.com 发送到 pqr.com(1 个发件人,1 个收件人)
  • 电子邮件 ID 501 已从 def.com 发送到 stu.com 和 pqr.com(1 个发件人,2 个收件人)
  • 电子邮件 ID 502 已从 abc.com 发送到 pqr.com(1 个发件人,1 个收件人)

我正在尝试编制一份报告,其中包含域之间发送的电子邮件总数,以生成以下内容:

[SendingDomainId|SendingDomainName|RecipientDomainId|RecipientDomainName|Total]

[600|abc.com|700|pqr.com|2]

[601|def.com|701|stu.com|1]

[601|def.com|700|pqr.com|1]

我正在尝试这个MERGE 语句,但UPDATE 部分不起作用。我最终得到一个包含与源表相同行的最终表。

MERGE #DomainsChord_TrafficData as T
USING #DomainsChord_DomainEmails AS S
ON (S.SendingDomainId = T.SendingDomainId AND
    S.RecipientDomainId = T.RecipientDomainId)
WHEN MATCHED THEN UPDATE 
    SET T.TotalEmails = T.TotalEmails+1
WHEN NOT MATCHED BY TARGET THEN  
    INSERT (SendingDomainId, SendingDomainName, RecipientDomainId,
            RecipientDomainName, TotalEmails)
    VALUES (S.SendingDomainId, S.SendingDomainName, 
            S.RecipientDomainId, S.RecipientDomainName, 1);

Table #DomainsChord_TrafficData 是合并前的空临时表。合并后,最终得到与源表相同的数据(#DomainsChord_DomainEmails)

有人能看出我哪里做错了吗?

提前致谢

【问题讨论】:

  • 您根本不需要MERGE。一个简单的SELECT GROUP BY 就可以了。

标签: sql sql-server tsql merge


【解决方案1】:

如果表之前是空的,那么就没有匹配来执行更新,它是不匹配的,因此插入运行。

【讨论】:

  • 我明白了。我误解了合并的工作原理。我认为它会单独遍历所有行,而实际上它是与源表的连接。
【解决方案2】:

在您的情况下,您不需要MERGE。您需要一个简单的SELECTGROUP BY 子句,如下所示:

SELECT SendingDomainId, SendingDomainName, RecipientDomainId, RecipientDomainName
     , COUNT(*) AS Total
  FROM #DomainsChord_DomainEmails
 GROUP BY SendingDomainId, SendingDomainName, RecipientDomainId, RecipientDomainName;

输出

SendingDomainId SendingDomainName RecipientDomainId RecipientDomainName Total
--------------- ----------------- ----------------- ------------------- -----------
600             abc.com           700               pqr.com             2
601             def.com           700               pqr.com             1
601             def.com           701               stu.com             1

MERGE 语句是将来自两个源的数据合并到一个目标中。如果您的目标 (#DomainsChord_TrafficData) 为空,则源 (#DomainsChord_DomainEmails) 中的所有数据都会按照您的描述在目标中结束。

参考:MSDNMERGE T-SQL

【讨论】:

  • 没错,好像我把事情过度复杂化了。非常感谢。
  • 当我回复 paulbarbin 时,我误解了合并的工作原理。一个明显的 RTFM 案例(如果有的话)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多