Conditional summation in PostgreSQL
I have a transactions
table which contains a category (category_id
), an amount (amount
) and a flag (managed
) which can be开发者_开发问答 true or false.
I would like to display a list of all categories with the total amounts of managed and not managed transactions, e.g.
Category | managed_transactions | unmanaged_transactions
Cat 1 | 124000 | 54000
Cat 2 | 4000 | 0
Cat 3 | 854000 | 1000000
Is there a way to do something like
Select category_id,
sum(amount) if (managed is true) as managed_transactions,
sum(amount) if (managed is false) as unmanaged_transactions
from transactions
I'm obviously stuck on the if managed is true
part...
Enjoy!
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
精彩评论