当我期望相同的结果时,2个查询返回不同的结果

时间:2014-10-23 13:27:34

标签: sql sql-server sql-server-2012

我有两个SQL查询,当我希望它们相同时返回不同的结果。

查询1:

SELECT COUNT(a.Id) 
FROM Accounts as a 
WHERE a.STATUS = 1 AND a.Type = 'A'
// returns 3529 results

查询2:

SELECT COUNT(a.Id) 
FROM Accounts as a 
INNER JOIN Payments as p ON a.Id = p.AccountId 
WHERE a.STATUS = 1 AND a.Type = 'A' AND p.STATUS = 1
// returns 3530 results

这是我们系统的冲突。要检索导致冲突的未知Id,我会在下面进行查询。

SELECT t1.Id 
FROM (SELECT a.Id 
      FROM Accounts as a 
      INNER JOIN Payments as p ON a.Id = p.AccountId 
      WHERE a.STATUS = 1 AND a.Type = 'A' AND p.STATUS = 1) AS t1
WHERE t1.Id NOT IN (SELECT a.Id 
                    FROM Accounts as a 
                    WHERE a.STATUS = 1 AND a.Type = 'A') 

此查询不返回任何结果,我不确定如何解决此问题。

A感谢您的关注解决了问题。

3 个答案:

答案 0 :(得分:0)

SELECT a.Id,count(*)
FROM Accounts as a
INNER JOIN Payments as p ON a.Id = p.AccountId
WHERE a.STATUS = 1
AND a.Type = 'A'
AND p.STATUS = 1
group by a.Id
having count(*)>1

答案 1 :(得分:0)

我认为有一个帐户通过p.STATUS付​​款<> 1

答案 2 :(得分:0)

不一致之处是由于一个帐户可以进行多次付款。例如,在Payments中,将记录如下:

{AccountId=1, STATUS = 1}
{AccountId=2, STATUS = 1}
{AccountId=2, STATUS = 1}

因此,如果您在此处进行INNER JOIN,则SELECT COUNT(a.Id)将计数AccountId=2两次。但是在查询1 中,它不会发生。这就是两个结果不同的原因。