我有以下查询:
SELECT cashtransactionstatus_id, SUM(cashtransaction_amount) AS cashtransaction_amount
FROM cash_transactions
WHERE cashpaymenttype_id = 1
GROUP BY (cashtransactionstatus_id);
此查询返回:
我如何只返回一位数字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
谢谢
答案 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