我有一个transactions
表,其中包含类别(category_id
),金额(amount
)和标志(managed
),可以是true或false。
我想显示所有类别的列表,其中包含托管和非托管交易的总金额,例如
Category | managed_transactions | unmanaged_transactions
Cat 1 | 124000 | 54000
Cat 2 | 4000 | 0
Cat 3 | 854000 | 1000000
有没有办法做类似
的事情Select category_id,
sum(amount) if (managed is true) as managed_transactions,
sum(amount) if (managed is false) as unmanaged_transactions
from transactions
我显然被困在if managed is true
部分......
答案 0 :(得分:21)
享受!
SELECT
category_id,
SUM( CASE WHEN managed THEN amount ELSE 0 END ) AS managed_transactions,
SUM( CASE WHEN managed THEN 0 ELSE amount END ) AS unmanaged_transactions
FROM
transactions
GROUP BY
category_id
ORDER BY
category_id