假设我有一个包含 USER_ID 和 AMOUNT 列的表。对于每一行,AMOUNT 列中可能存在正数或负数。
我正在寻找一种从该表中进行选择的方法,以便结果具有 id、金额的总和、仅正值的金额的总和、每个 USER_ID 的负值的金额的总和。我可以很容易地进行求和,但我试图弄清楚如何做最后两列。
我对 SQL 还是很陌生。我知道一些基础知识,但我对这一点感到困惑。我有一种感觉,我不能用一个 SELECT 语句来做到这一点。任何帮助都会很棒。
The LEAST and GREATEST Oracle functions will do the trick (not sure wheather they are ANSI or Oracle only ):
select
user_id
sum(amount) total,
sum(least(amount,0)) total_negs,
sum(greatest(amount,0)) total_pos
from
my_table
group by
user_id
LEAST returns the smallest value from a list of parameters. If you pass amount and zero, it will filter positive numbers out.
GREATEST will filter out negative numbers.
This solution will not work with averages since zeroes will alter the average.
select
user_id
sum(amount) total,
sum(case when amount < 0 then amount else 0 end) total_negs,
sum(case when amount > 0 then amount else 0 end) total_pos
from
my_table
group by
user_id
你需要这样的东西。