0

This question was born in my mind looking at this kind of code:

select sum(value)
 into positive
 from my_table
 where value > 0;
 select sum(value)
 into negative
 from my_table
 where value < 0;

This works well for take the totals of this table.

But, my question is how I can get the sub-totals of my_table using only a statement.

expected result:

Having this data on my_table

VALUE
-----
 1.0
 -2.0
 3.0
 -4.0
 5.0
 -6.7
 8.9

I'd a DML statement who can give me this output

positive | negative
---------+---------
 17.9 | -12.7

Is this kind of operation possible? If yes, how can i get it?

asked Apr 16, 2015 at 11:40

1 Answer 1

2
SQL> r
 1 with t as (
 2 select 1.0 as x from dual
 3 union all select -2.0 as x from dual
 4 union all select 3.0 as x from dual
 5 union all select -4.0 as x from dual
 6 union all select 5.0 as x from dual
 7 union all select -6.7 as x from dual
 8 union all select 8.9 as x from dual)
 9 select sum(case when x > 0 then x else 0 end) as sum_of_positives,
 10 sum(case when x < 0 then x else 0 end) as sum_of_negatives
 11* from t
SUM_OF_POSITIVES SUM_OF_NEGATIVES
---------------- ----------------
 17,9 -12,7
answered Apr 16, 2015 at 12:07
2
  • 1
    Hopefully Oracle one day supports the filter syntax: select count(*) filter (where x > 0) as positive, count(*) filter (where x < 0) as negative from t; This works in PostgreSQL 9.4+, if anyone is interested. Commented Apr 16, 2015 at 15:17
  • 2
    @colin'thart This page has a handy table about what dbs support filter functionality: filter — Selective Aggregates. Commented Sep 6, 2021 at 14:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.