【发布时间】:2015-10-30 08:58:37
【问题描述】:
我在 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 $1,000.
我使用 CTE 得出以下答案。它从表中删除 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 exists 与having sum(totaldue) >= 1000 一起使用,它也会产生5696 行。我不明白为什么查询会产生不同的结果 - EXISTS 和 < 1000 不应该产生与 NOT EXISTS 和 >=1000? 相同的结果
我查看了出现在NOT EXISTS、>=1000 版本中的 496 行,并确定customerid 不存在于salesorderheader 表中(即他们没有下订单)。但是为什么NOT EXISTS 版本会捕获这个而EXISTS 没有呢?
【问题讨论】:
-
你试过看看有多少订单的总和=1000?
-
@vkp 没有一个分组的总和 = 1000。我会发布查询,但看起来 cmets 不允许格式化 - 如果您希望我发布它,请告诉我。
标签: sql sql-server exists sql-server-2014 not-exists