简体   繁体   English

MySQL将列拆分为多列

[英]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 :) 我不是sql专家,所以我希望有一个我不知道的查询:)

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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