我想减去同一表中的行(where子句不同)。
SELECT SUM(`balance`) AS `balance` FROM `vouchers` WHERE `type`='CP' AND `post_status`='yes' GROUP BY `interactive_person`;
上面的查询为我提供了一些理想的结果!第二个查询是
SELECT SUM(`balance`) AS `balance` FROM `vouchers` WHERE `type`='CR' AND `post_status`='yes' GROUP BY `interactive_person`;
这些查询返回的行多于交互人分组,我希望它减去交互人(是数字)相同但类型改变的记录。简而言之,它就像CashReceipt-CashPayment。我将第一个查询用作第二个查询的子查询,但错误显示该子查询返回的行多。我需要帮助解决这个问题!
答案 0 :(得分:0)
您可以使用case
在同一查询中计算sum()
SELECT
SUM(CASE WHEN `type`='CP' THEN `balance` ELSE 0 END) AS CP_balance,
SUM(CASE WHEN `type`='CR' THEN `balance` ELSE 0 END) AS CR_balance,
SUM(CASE WHEN `type`='CP' THEN `balance` WHEN `type`='CR' THEN -1 * `balance` ELSE 0 END) AS diff
FROM `vouchers`
WHERE `post_status`='yes'
GROUP BY `interactive_person`;