select正负值之和:postgres
select the sum of positive and negative values: 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
我愿意
选择负值,计算它们的sum/average
选择正值,计算它们的sum/average
在 2 列中表示它们
想要的结果
340.61 -768.27
当我使用 UNION
运算符时,我得到两行。使用 CASE.. WHEN..
时,它将余额分组,我收到多行。
我的 postgres 查询中还有其他聚合函数,因此我希望它们中的每一个都显示在单独的列中。
有什么办法吗?
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)
这个?..为什么不使用 case 两次?
在 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;
我有一个简单的任务是计算用户帐户余额的总和或平均值。
用户在当月可能有负余额或正余额。这是当月用户余额的示例
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
我愿意
选择负值,计算它们的sum/average
选择正值,计算它们的sum/average
在 2 列中表示它们
想要的结果
340.61 -768.27
当我使用 UNION
运算符时,我得到两行。使用 CASE.. WHEN..
时,它将余额分组,我收到多行。
我的 postgres 查询中还有其他聚合函数,因此我希望它们中的每一个都显示在单独的列中。 有什么办法吗?
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)
这个?..为什么不使用 case 两次?
在 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;