将具有重复值的行转换为列-MySQL

时间:2019-05-08 21:31:02

标签: mysql sql

我有一个表'A',看起来像:

_______________________________________________________________
|query_id |   query      |  response   |user_response_count    |
|--------------------------------------------------------------- 
|   1     |   acne       |   BothBad   |       2               |
|   1     |   acne       |  BothGood   |       1               |
|   2     |   asthma     |   BothBad   |       1               |
|   2     |   asthma     |   product 1 |       1               |
|   2     |   asthma     |   BothGood  |       1               |
|   3     |   bell palsy |   product 2 |       2               |
|   3     |   bell palsy |   BothGood  |       1               |
 ---------------------------------------------------------------

我想编写一个查询以获取如下内容:

__________________________________________________________________________________
| query_id |   query   |   BothGood   |   BothBad   |   Product 1 |   Product 2   |
-----------------------------------------------------------------------------------
|    1     |    acne   |         1    |    2        |       0     |         0     |
|    2     |   asthma  |         1    |    1        |       1     |         0     |
|    3     | bell palsy|         1    |    0        |       0     |         2     |
-----------------------------------------------------------------------------------

“ user_response_count”列实际上说,有2个用户选择了“痤疮”查询的“ BothBad”选项。

我知道,通过使用max,我可以将行更改为该列,但在此情况下要达到最大难度是困难的。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

有条件的聚合:

select query_id, query,
       sum(case when response = 'BothGood' then cnt else 0 end) as BothGood,
       sum(case when response = 'BothBad' then cnt else 0 end) as BothBad,
       sum(case when response = 'product 1' then cnt else 0 end) as product1,
       sum(case when response = 'product 2' then cnt else 0 end) as product2
from a
group by query_id, query;

答案 1 :(得分:0)

您可以将conditional aggregation用作

select query_id, query,
   max( coalesce(case when response = 'BothGood'  then user_response_count end,0) ) 
     as BothGood,
   max( coalesce(case when response = 'BothBad'   then user_response_count end,0) ) 
     as BothBad,
   max( coalesce(case when response = 'product 1' then user_response_count end,0) ) 
     as Product_1,
   max( coalesce(case when response = 'product 2' then user_response_count end,0) ) 
    as Product_2
  from tableA
 group by query_id, query

Demo