Mysql将列拆分成多列

时间:2014-09-15 12:27:41

标签: mysql sql

我有一张表:

  id  |  cat  |  price
----------------------
  0   |   1   |  2
  0   |   2   |  1 
  0   |   1   |  1
  1   |   1   |  31
  1   |   2   |  5
----------------------

我喜欢选择它:

  id  |  cat1_price  |  cat2_price  
----------------------------------
  0   |       3      |      1
  1   |      31      |      5
----------------------------------

到目前为止我的查询:

SELECT SUM(`price`) as cat1_price FROM price_table WHERE cat = 1 GROUP BY id

可以获得所需的列之一。 我如何兼得?

我也尝试过这样的事情:

 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

效果太慢了。实际的表非常大,并且有一些连接。

我不是sql guru,所以我希望有一个查询,我不知道:)

1 个答案:

答案 0 :(得分:4)

只需使用条件聚合:

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;