Reputation: 173
I have a simple task of computing the sum or average of a user's account balance.
The user may have a negative balance or a positive balance during the month. Here is an example of a user balance during the current month
95.63
97.13
72.14
45.04
20.04
10.63
-29.37
-51.35
-107.55
-101.35
-157.55
-159.55
-161.55
I would like to
choose the negative values, compute their sum/average
choose the positive values, compute their sum/average
represent them in 2 columns
Desired result
340.61 -768.27
When I use the UNION
operator, I get two rows. When using CASE.. WHEN..
it groups the balances, and I receive multiple rows.
I have other aggregate functions in my postgres query, so I want each of them to be shown in a separate column. Is there any way to do that?
Upvotes: 5
Views: 9592
Reputation: 121574
In Postgres 9.1:
select
sum(case when val >= 0 then val end) as positive,
sum(case when val < 0 then val end) as negative
from the_data;
An alternative solution for Postgres 9.4+:
select
sum(val) filter (where val >= 0) as positive,
sum(val) filter (where val < 0) as negative
from the_data;
Upvotes: 12
Reputation: 51446
v=# select sum(case when f < 0 then f end) n, sum(case when f >= 0 then f end) p from s170;
n | p
---------+--------
-768.27 | 340.61
(1 row)
this?.. why not using case twice?
Upvotes: 5