EXISTS 和小于从 NOT EXISTS 和大于产生不同的结果

EXISTS and less than producing different result from NOT EXISTS and greater than

我在AdventureWorks2012数据库中使用SQL Server 2014 Express,通过T-SQL教材学习。我正在做以下练习:

Delete the rows from the dbo.demoCustomer table if the sum of the TotalDue     
from the dbo.demoSalesOrderHeader table for the customer is less than ,000. 

我使用 CTE 得出了以下答案。它从 table.

中删除了 5200 行
;with broke as
   (select c.customerid
   , sum(soh.totaldue) 'custtotal'
   from democustomer c
   inner join demosalesorderheader soh on soh.customerid = c.customerid
   group by c.customerid
   having sum(soh.totaldue) < 1000)
delete c
from democustomer c
where exists
   (select *
   from broke b
   where b.customerid = c.customerid);

我查看了 texbook 的答案,它给出了以下内容。与我的查询不同,它删除了 5696 行,比我自己的多了 496 行。

delete c
from dbo.democustomer c
where not exists
   (select *
   from dbo.demosalesorderheader soh
   where c.customerid = soh.customerid
   group by soh.customerid
   having sum(totaldue) >=1000);

如果我改变我的方法并使用 not existshaving sum(totaldue) >= 1000,它也会产生 5696 行。我不明白的是为什么查询产生不同的结果 - EXISTS< 1000 不应该产生与 NOT EXISTS>=1000?

相同的结果

我查看了 NOT EXISTS>=1000 版本中显示的 496 行,并确定 customerid 不存在于 salesorderheader 版本中table(即他们没有下订单)。但是为什么 NOT EXISTS 版本会捕捉到这一点而 EXISTS 却没有?

您理解问题,即 demosalesorderheader 中的 NULL/missing 个值。

您说 exists 的版本要求客户同时存在于 table 中,总和小于 1000。

备选版本没有关于 table 中客户存在的条件。据推测,默认值为0.

您可以更改查询以获得相同的结果:

with broke as (
     select c.customerid, coalesce(sum(soh.totaldue), 0) as custtotal
     from democustomer c left join
          demosalesorderheader soh
          on soh.customerid = c.customerid
     group by c.customerid
     having coalesce(sum(soh.totaldue), 0) < 1000
    )

left join会留住所有的顾客。