用两个不同条件的mysql在同一列上求和

时间:2019-04-12 11:03:12

标签: mysql sql

我有一个名为 Order 的表,其架构为

user_id, state    amount
11       success  100
11       FAILED   10
11       FAILED   10
11       success  17

状态可以有两个值(成功/失败)。

我想获取sum(amount) when state = "SUCCESS" - sum(amount) when state = "FAILED" 表示成功时的总差额-失败时的总差额。

我可以通过2个查询解决此问题。

A = select id, sum(amount) when state = "SUCCESS"
B = select id, sum(amount) when state = "FAILED"

解决方案将为 A-B 。 有什么方法可以在单个sql查询中实现?

3 个答案:

答案 0 :(得分:1)

用例何时

    select user_id,sum(case when state = 'SUCCESS' then amount else 0 end)-sum(case when state = 'FAILED' then amount else 0 end)
from table group by user_id

答案 1 :(得分:1)

使用条件聚合:

select id,
       sum(case when state = 'SUCCESS' then amount else - amount end) as total
from t
where state in ('SUCCESS', 'FAILED')
group by id;

我假设您希望按id来获得此总和,而不是表格中的总和。

答案 2 :(得分:0)

select sum(case when state = "SUCCESS" then amount else o end) -
    sum(case when state = "FAILED" then amount else o end)
    from tbl
group by userid