简体   繁体   中英

Mysql split column into multiple columns

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 :)

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM