我试图在mysql查询中使用case语句将行转换为列。我在这里看到过这样的其他问题,但由于某些原因我不能让它工作。这是示例原始数据。
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
这是设置,我正在尝试...
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;
然而我得到的却是......
last_name Q1 Q2 Q3 Q4
Jones correct
Smith incorrect
答案 0 :(得分:2)
您的查询中需要聚合函数:
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;
在大多数数据库中,您的查询版本无法编译。如果question_number
子句中没有group by
,则会收到错误。 MySQL允许语法,但只返回单行的任意值。 max()
确保处理所有行。