Using case to convert column values to row values in mysql

对着背影说爱祢 提交于 2020-01-07 02:21:08

问题


I am trying to use case statements in a mysql query to convert rows to columns. I have seen other questions like this here, but I can't get it to work for some reason. Here is example raw data.

last_name  question_number  result
Jones        1               correct
Jones        2               correct
Jones        3               incorrect
Jones        4               correct
Smith        1               incorrect
Smith        2               correct
Smith        3               correct
Smith        4               incorrect

Here is what I want to end up with

last_name    Q1         Q2         Q3         Q4
Jones        correct    correct    incorrect  correct
Smith        incorrect  correct    correct    incorrect

Here is the set-up, and what I was trying...

drop table if exists test_case;
create table test_case (
    last_name varchar(30),
    question_number int,
    result varchar(30)
);

insert into test_case 
values ('Jones',1,'correct'), ('Jones',2,'correct'), ('Jones',3,'incorrect'), ('Jones',4,'correct'),
('Smith',1,'incorrect'), ('Smith',2,'correct'), ('Smith',3,'correct'), ('Smith',4,'incorrect');

select * from test_case;

select 
    last_name,
    case
        when question_number = 1 then result
        else null
    end as Q1,
    case
        when question_number = 2 then result
        else ''
    end as Q2,
    case
        when question_number = 3 then result
        else ''
    end as Q3,
    case
        when question_number = 4 then result
        else ''
    end as Q4
from
    test_case
group by last_name;

What I get back however is this...

 last_name    Q1         Q2         Q3         Q4
Jones        correct    
Smith        incorrect  

回答1:


You need aggregation functions in your query:

select last_name,
       max(case when question_number = 1 then result end) as Q1,
       max(case when question_number = 2 then result end) as Q2,
       max(case when question_number = 3 then result end) as Q3,
       max(case when question_number = 4 then result end) as Q4
from test_case
group by last_name;

In most databases, your version of the query would not compile. You would get an error to the effect that question_number is not in the group by clause. MySQL allows the syntax, but then just returns arbitrary values for a single row. The max() makes sure that all the rows are processed.



来源:https://stackoverflow.com/questions/23377374/using-case-to-convert-column-values-to-row-values-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!