Reputation: 2000
I have table with columns type(0 or 1), amount(int)
I need query what returns 2 params: sum amount for type = 1 and sum amount for type = 0
2 queries:
SELECT SUM(amount) AS income FROM table WHERE type = 0;
SELECT SUM(amount) AS expense FROM table WHERE type = 1;
But can i return these params using only 1 query?
Upvotes: 2
Views: 55
Reputation: 204766
SELECT sum(case when type = 0
then amount
else 0
end) AS income,
sum(case when type = 1
then amount
else 0
end) AS expense
FROM table
Upvotes: 1
Reputation: 360702
SELECT SUM(amount), IF(type=0, 'income', 'expense') AS type
FROM table
GROUP BY type
Upvotes: 3