任何人都可以简化这个MYSQL查询
同一个表我想用1种类型的值减去另一种类型的值
ex:sum( type1 ) - sum (type 2)
SELECT (SELECT sum(exp_amount) FROM `expenses` WHERE `account_id` = 1 && `type_id` = 2)
- (SELECT sum(exp_amount) FROM `expenses` WHERE `account_id` = 1 && `type_id` = 1) AS balance FROM `expenses`
LIMIT 0 , 1
指导我如何在Cake php中处理此查询注意:不直接使用此查询 - >查询(...)
答案 0 :(得分:2)
通过使用
下面的基于案例的聚合,您可以通过单次扫描得到平衡SELECT Coalesce(sum(CASE WHEN type_id=2 THEN exp_amount END), 0) - Coalesce(sum(CASE WHEN type_id =1 THEN exp_amount END),0) AS balance
FROM expenses
WHERE account_id = 1
AND type_id IN (1,2)