gpt4 book ai didi

sql - 选择正负值之和 : postgres

转载 作者:行者123 更新时间:2023-11-29 14:04:41 25 4
gpt4 key购买 nike

我有一个简单的任务是计算用户账户余额的总和或平均值。

用户在当月可能有负余额或正余额。这是当月用户余额的示例

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 查询中还有其他聚合函数,因此我希望它们中的每一个都显示在单独的列中。有什么办法吗?

最佳答案

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

关于sql - 选择正负值之和 : postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44647849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com