Search code examples
sqlpostgresqlaggregate-functionspostgresql-9.1

select the sum of positive and negative values: postgres


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

  1. choose the negative values, compute their sum/average

  2. choose the positive values, compute their sum/average

  3. 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?


Solution

  • 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?