SUM和Subtract结果取决于Mysql查询中的列结果

时间:2015-04-12 06:59:13

标签: mysql sql

我有以下查询:

SELECT cashtransactionstatus_id, SUM(cashtransaction_amount) AS cashtransaction_amount 
    FROM cash_transactions 
    WHERE cashpaymenttype_id = 1 
    GROUP BY (cashtransactionstatus_id);

此查询返回:

enter image description here

我如何只返回一位数字endtotal减去和总和,具体取决于列cashtransactionstatus_id?例如:

SUM Status(1,3): 1195.00 as col1

SUM Status(2,4,5): 430.00 as col2

然后show (col1 - col2) AS endtotal = 765.00

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

SELECT SUM(CASE WHEN cashtransactionstatus_id IN (1,3) THEN cashtransaction_amount END) -
       SUM(CASE WHEN cashtransactionstatus_id IN (2,4,5) THEN cashtransaction_amount END) AS endtotal
FROM cash_transactions 
WHERE cashpaymenttype_id = 1

SQL Fiddle Demo