Преобразовать строку с повторяющимися значениями в столбец - MySQL - PullRequest
0 голосов
/ 09 мая 2019

У меня есть таблица «А», которая выглядит примерно так:

_______________________________________________________________
|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» для запроса «acne».

Я знаю, что с помощью max я могу изменить свои строки на столбец, но здесь это будет сложно по максимуму. Есть мысли?

Ответы [ 2 ]

2 голосов
/ 09 мая 2019

Условное агрегирование:

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;
0 голосов
/ 09 мая 2019

Вы можете использовать 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

Демо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...