如何编写SQL查询以汇总每个用户的存款和取款

时间:2019-07-08 01:48:28

标签: sql postgresql

我有下面的表格,其中包含存款和取款清单。我需要写查询 以获得每位用户的全部存款和提款

样品输入表

enter image description here

,输出应该是

enter image description here

请大家帮我写一个查询

我尝试过的sql代码是

select name, 
       sum (case when  money >= 0 then money else 0 end) as sum_of_deposits,
       sum (case when money < 0 then  money else 0 end) as sum_of_withdrawals 
from transfers GROUP BY name

4 个答案:

答案 0 :(得分:0)

如果您使用的是PostgreSQL 9.4或+,则可以使用FILTER子句进行聚合功能,这是该版本的新功能,请与group by子句组合以进行用户分组,例如:

CREATE TABLE so (u text, v int);

INSERT INTO so VALUES ('a',-10000), ('b',10000),('a',2000),('c',-100);

SELECT u, 
sum(v) FILTER (WHERE v>=0) dep,
sum(abs(v)) FILTER (WHERE v<0)withdraws
FROM so
GROUP BY 1;

尝试根据您的情况调整此示例,abs函数返回作为参数传递的数字的绝对值,这是为了避免出现负数

答案 1 :(得分:0)

我认为您的代码基本上是正确的。唯一的问题是标志:

select name,
       sum(case when money > 0 then money else 0 end) as sum_of_deposits,
       sum(case when money < 0 then -money else 0 end) as sum_of_withdrawals
from transfers 
group by name;

我同意filter是回答问题的更直接方法:

select name,
       sum(v) filter (where v > 0) as sum_of_deposits,
       sum(- v) filter (where v < 0) as num_of_withdrawals
from transfers
group by name;

但是case也是一个合理的解决方案。

答案 2 :(得分:0)

此示例与“ GROUP BY”功能一起使用。 您的答案非常接近解决方案,但您必须记住,“ CASE”函数会详细说明所有通过的值(=货币)。没有分开。

SELECT name, 
    sum(deposits) as sum_of_deposits, 
    sum(withdrawals) as sum_of_withdrawals
FROM (
    SELECT name,
        CASE 
            WHEN (money>0) THEN sum(money)
            ELSE (0)
        END as deposits,
        CASE 
            WHEN (money<0) THEN sum(abs(money))
            ELSE (0)
        END as withdrawals
    FROM transfers
    GROUP BY money
)
GROUP BY name;

结果:results.sqliteDB

答案 3 :(得分:0)

COALESCE 函数可用于将 null 替换为 0

 select name,
 coalesce(sum(case when amount>0 then amount end), 0) as sum_deposits,
 coalesce(sum(case when amount<0 then amount end), 0) as sum_transfers
 from transfers
 group by name