Ozerich
Ozerich

Reputation: 2000

In 1 query: 2 results, using 2 conditions

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

Answers (2)

juergen d
juergen d

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

Demo

Upvotes: 1

Marc B
Marc B

Reputation: 360702

SELECT SUM(amount), IF(type=0, 'income', 'expense') AS type
FROM table
GROUP BY type

Upvotes: 3

Related Questions