Reputation: 905
I have a table like:
id | cat | price
----------------------
0 | 1 | 2
0 | 2 | 1
0 | 1 | 1
1 | 1 | 31
1 | 2 | 5
----------------------
I like to select it like:
id | cat1_price | cat2_price
----------------------------------
0 | 3 | 1
1 | 31 | 5
----------------------------------
My query so far:
SELECT SUM(`price`) as cat1_price FROM price_table WHERE cat = 1 GROUP BY id
which works to get one of the needed columns. How can I have both?
I also tried something like:
SELECT SUM(`price`) as cat1_price
(SELECT SUM(`price`) FROM price_table WHERE cat = 2) as cat2_price
FROM price_table WHERE cat = 1 GROUP BY id
which works too slow. The actual table is pretty big and has some some joins.
I'm not sql guru, so I hope there is a query for this I'm not aware of :)
Upvotes: 1
Views: 1247
Reputation: 1269503
Just use conditional aggregation:
SELECT id, SUM(case when cat = 1 then `price` else 0 end) as cat1_price,
SUM(case when cat = 2 then `price` else 0 end) as cat1_price
FROM price_table
GROUP BY id;
Upvotes: 5