简体   繁体   中英

How to return only non-zero values from a Select sum statement

I have a query returning 2 columns and multiple rows. How do I only return a sum value which is not 0 or null?

Table " audit " is like this:

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

I am checking to see if the values placed into the amount column balance for 1 and 0 values in the dr column.

This query works and returns a few thousand rows with 0 as the sum result and 2 with a value in the sum. I only want to return the rows with a value for the sum.

Any help would be much appreciated.

Use 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

Also, try a query like this: (it doesn't require any additional calculations)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM