有谁知道为什么以下2个查询的结果不能与第3个查询的结果相加?
SELECT COUNT(leadID) FROM leads
WHERE makeID NOT IN (SELECT uploadDataMapID FROM DG_App.dbo.uploadData WHERE uploadID = 3 AND uploadRowID = 1)
AND modelID NOT IN (SELECT uploadDataMapID FROM DG_App.dbo.uploadData WHERE uploadID = 3 AND uploadRowID = 2)
SELECT COUNT(leadID) FROM Leads
WHERE makeID IN (SELECT uploadDataMapID FROM DG_App.dbo.uploadData WHERE uploadID = 3 AND uploadRowID = 1)
OR modelID IN (SELECT uploadDataMapID FROM DG_App.dbo.uploadData WHERE uploadID = 3 AND uploadRowID = 2)
SELECT COUNT(leadID) FROM Leads
第一个查询是我需要的计数。第二个是告诉用户根据DG_App.dbo.uploadData表的内容抑制了多少记录。第三个查询只是所有记录的直接计数。
当我运行这些查询1的结果时,查询2的结果会出现大约46K记录,小于整个表的计数。我曾经使用()对WHERE语句进行分组,但这根本没有改变计数。
这是MSSQL Server 2012。
对此的任何输入都会很棒。
由于
答案 0 :(得分:4)
你有任何NULL值吗?它们不会出现在第一次的第一次,我认为你错过了那些。
SELECT Count(leadID) FROM Leads WHERE makeID is Null or modelID is null
编辑:我必须添加一些注意事项:因为有一个AND和OR条件,事情会变得复杂一点!
这意味着在前两个查询中,一些记录已经计入Null,而其他记录则没有。这就是你想念的:
您遗漏了makeID
和modelID
都为空的记录:
SELECT Count(leadID) FROM Leads WHERE makeID is Null and modelID is null
但是你也错过了makeID
为空的记录,modelID
不为空且不在第二个子查询中:
SELECT Count(leadID) FROM Leads
WHERE makeID is Null
AND modelID NOT IN (...)
modelID
为空且makeID
不在第一个子查询中的那些:
SELECT Count(leadID) FROM Leads
WHERE makeID is NOT IN (...)
AND modelID is Null
答案 1 :(得分:2)
我能想到的三个案例:
SELECT count(leadID) FROM leads WHERE makeID IS NULL OR modelID IS NULL
SELECT count(leadID)
FROM leads AS l INNER JOIN DG_App.dbo.uploadData AS u ON l.makeID = u.uploadDataMapID
WHERE u.uploadID <> 3 OR u.uploadRowID <> 1
SELECT count(leadID)
FROM leads AS l INNER JOIN DG_App.dbo.uploadData AS u ON l.modelID = u.uploadDataMapID
WHERE u.uploadID <> 3 OR u.uploadRowID <> 2
这三个查询应该为您提供缺失的记录。