2017-06-20 79 views
0

我有一個簡單的任務來計算用戶帳戶餘額的總和或平均值。選擇正值和負值的總和:postgres

用戶在該月份可能有負餘額或正餘額。這裏是當月

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 

期間用戶平衡的一個例子,我想

  1. 選擇負值,計算它們的總和/平均

  2. 選擇正值,計算它們的總和/平均值

  3. 表示它們在2列

期望的結果

340.61  -768.27 

當我使用UNION運營商,我得到兩行。當使用CASE.. WHEN..時,它將天平分組,並且我收到多行。

我在我的postgres查詢中有其他聚合函數,所以我希望他們每個人都顯示在一個單獨的列。 有沒有辦法做到這一點?

回答

1
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) 

這個?..爲什麼不用兩次?

1

在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; 

爲Postgres的9.4+的替代解決方案:

select 
    sum(val) filter (where val >= 0) as positive, 
    sum(val) filter (where val < 0) as negative 
from the_data;