在其他字段

时间:2018-04-30 10:00:39

标签: mysql sql

我的数据存储在mysql中。

我的表格数据如下

3   credit  500.00
3   debit   500.00
4   credit  300.00
4   debit   300.00
5   credit  300.00
5   debit   300.00
6   credit  300.00
6   debit   300.00

我想写一个查询来写数据 客户ID,信用卡,借记卡,final_amount

最终金额= credit-debit

有人可以帮我查询吗?

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

select customerid, 
       sum(case when type = 'credit' then amount else 0 end) as credit,
       sum(case when type = 'debit' then amount else 0 end) as debit,
       sum(case when type = 'credit' then amount
                when type = 'debit' then - amount
                else 0
           end) as credit
from t
group by customerid;
相关问题