错误通常但在EXISTS子查询中运行

时间:2012-08-20 10:37:18

标签: sql sql-server-2008-r2

以下是否存在问题?

DELETE a
FROM WHAnalysis.dbo.tb_r12027dxi_CalculatedData a
WHERE EXISTS
        (
        SELECT * 
        FROM WHAnalysis.dbo.tb_r12027dxi_CalculatedData b
        WHERE 
            b.[Past28Days] = 1 AND
            a.[Index] = b.[Index]
        HAVING SUM(b.Amount) = 0
        )

原因我对使用上面的脚本有点不安,如果我运行以下错误:

SELECT * 
FROM WHAnalysis.dbo.tb_r12027dxi_CalculatedData b
WHERE 
    b.[Past28Days] = 1
HAVING SUM(b.Amount) = 0

我理解为什么这个脚本错误=> select没有被分组,因此处理器不喜欢HAVING子句中的聚合。

但是作为子查询,这个错误不会发生 - 为什么?这是一个有问题的方法吗?

修改

使用以下内容结束:

DELETE a
FROM WHAnalysis.dbo.tb_r12027dxi_CalculatedData a
WHERE a.[Index] IN
    (
    SELECT [Index] 
    FROM WHAnalysis.dbo.tb_r12027dxi_CalculatedData
    WHERE [Past28Days] = 1
    GROUP BY [Index] 
    HAVING SUM(Amount) = 0
    )

但正如回答中所建议的那样,通过简单地将GROUP BY添加到子查询中,以下内容更具可读性:

DELETE a
FROM WHAnalysis.dbo.tb_r12027dxi_CalculatedData a
WHERE EXISTS
    (
    SELECT * 
    FROM WHAnalysis.dbo.tb_r12027dxi_CalculatedData b
    WHERE 
            b.[Past28Days] = 1 AND
            a.[Index] = b.[Index]
    GROUP BY b.[Index]
    HAVING SUM(b.Amount) = 0
    )

1 个答案:

答案 0 :(得分:2)

省略分组并仍然执行汇总是合法的,因此having仍然是限制结果的一种方式:

select sum(x)
from
(
  select 1 x union all select 2
) a
having sum(x) = 3

Exists()有效,因为选择列表中的所有内容都会被忽略。 Exists()仅查找行,并在找到行后立即终止。您可以添加group by b.Index以使以后查看代码的任何人都明白意图,或者使用内部联接和派生表重写它。

DELETE a
FROM WHAnalysis.dbo.tb_r12027dxi_CalculatedData a
INNER JOIN
        (
        SELECT b.[Index]
        FROM WHAnalysis.dbo.tb_r12027dxi_CalculatedData b
        WHERE 
            b.[Past28Days] = 1
        GROUP BY b.[Index]
        HAVING SUM(b.Amount) = 0
        ) b1
   ON a.[Index] = b1.[Index]