0

I'm trying to sum columns in a table and then return each column and value as a separate row, but only if the sum is > 0. Here's an example table

…   stuff   widget  toast   …
-   -----   ------  -----   -
…   0       0       1       …
…   1       0       3       …
…   2       0       1       …
…   0       0       1       …
…   0       0       0       …

Summing the columns is easy enough

select sum(stuff) as stuff, sum(widget) as widget, sum(toast) as toast from table

Which produces this output

stuff   widget  toast
-----   ------  -----
3       0       6

But what I actually want to end up with is this (notice that widget is missing since the sum is 0)

thing   count
----    -----
stuff   3
toast   6

Any advice?

0

1 Answer 1

2

Here you go:

SELECT 'stuff' as thing, sum(stuff) `count` FROM foo HAVING `count` > 0
UNION
SELECT 'widget', sum(widget) s FROM foo HAVING s > 0
UNION
SELECT 'toast', sum(TOAST) t FROM foo HAVING t > 0

http://sqlfiddle.com/#!2/b586f/7

Aliases in first SELECT determine the column names of the result, aliases in following SELECTs don’t matter, therefor I used short ones.

And HAVING the respective sum > 0 eliminates the widget column in the result as requested.

Only feasible for that small amount of original columns though – for a higher number of columns you probably wouldn’t want to do that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.