如何仅从Select sum语句返回非零值

时间:2012-06-14 09:13:32

标签: sql select sum firebird

我有一个返回2列和多行的查询。我如何只返回一个非0或null的和值?

表“audit”是这样的:

parent_link   integer;
dr            smallint
amount        decimal(18,2)

select parent_link, sum(case dr when 1 then amount else -amount end)
from audit where books = 3 group by parent_link

我正在检查数据列中的值是否在dr列中为1和0值平衡。

此查询有效并返回几千行,其中0为总和结果,2为总和值。我只想返回带有总和值的行。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:9)

使用having

select parent_link, sum(case dr when 1 then amount else -amount end)
from audit
where books = 3
group by parent_link
having sum(case dr when 1 then amount else -amount end) <> 0

答案 1 :(得分:2)

另外,尝试这样的查询:(它不需要任何额外的计算)

SELECT _inner._SUM FROM
(
    SELECT parent_link, SUM(CASE dr WHEN 1 THEN amount ELSE -amount END) AS _SUM
      FROM audit WHERE books = 3 GROUP BY parent_link
) AS _inner
WHERE _inner._SUM <> 0