Skip to content
Advertisement

How to Return Separate Sums of Columns if Initial Value in row is 0 in SQL

I am trying to write a SQL query that will return unique rows of sums of shipped part numbers per customer depending on if the value is negative or positive. For example:

If we shipped 20 of part Z to customer A twice, and they returned 6 parts back to us, it would display:

After running query, expected results:

The query I have come up with is:

But I get error:

Column invalid. Must be a group by column: Ship_Quantity in SELECT LIST.

When I add the “Ship_Quantity” to my GROUP BY, it does not give accurate results:

Original Input:

After Query:

How would I go about doing this?

Advertisement

Answer

Use the function SIGN() in the GROUP BY clause:

If your database does not support the function SIGN() use a CASE expression:

See the demo.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement