比较表并查找不匹配计数的元素

时间:2016-02-18 09:25:06

标签: sql sql-server-2008

我有两张桌子

表1

enter image description here

表2

enter image description here

现在我想要那些RequestId和Table1中那些与Table2不同的RequestId的计数,例如,输出应该是

enter image description here

我可以通过以下查询从这两个表中获取单个计数和RequestId:

select RequestId, Count(RequestId) AS [Count] from Table1 group by RequestId

但是如何在一个查询中比较两个表,任何帮助都会很好,如果没有执行循环直到它执行它的唯一方法将是好的,因为这两个表中有很多记录,图像共享这里只是为了理解。

2 个答案:

答案 0 :(得分:1)

您将查询用作FROM中的子查询。外连接表2,因为其中包含所有请求ID的行:

select t1.requestid, t1.cnt - coalesce(t2.cnt, 0) as diff
from (select requestid, count(*) as cnt from table1 group by requestid) t1
left join (select requestid, count(*) as cnt from table2 group by requestid) t2
  on t2.requestid = t1.requestid
where (t1.cnt - coalesce(t2.cnt, 0)) > 0;

答案 1 :(得分:0)

如果我没有弄错你,那么你可以使用你的查询来检查每个表中的RequestId的数量,然后通过计数加入它们甚至不是。并做简单的数学运算:

select t1.RequestId, (t1.Count - t2.Count) as count 
 from
 (select RequestId, Count(RequestId) AS [Count] from Table1 group by RequestId)t1
left join(select RequestId, Count(RequestId) AS [Count] from Table2 group by RequestId)t2
on t1.RequestId = t2.RequestId  
where t1.Count <> t2.Count