Mysql中查询(数据库中的)纵向转(查询结果显示为)横向.
id name day
1 liu 1
2 liu 3
3 wang 1
4 wang 2
5 wang 4
查询结果:
name d_1 d_2 d_3 d_4
liu 1 1
liu 1 1 1 展开
1、在mysql环境,创建数据库表,
create table test_data1(id int, name VARCHAR(20), day VARCHAR(20))
2、插入测试数据,
insert into test_data1 values(1,'liu',1);
insert into test_data1 values(2,'liu',3);
insert into test_data1 values(3,'wang',1);
insert into test_data1 values(4,'wang',2);
insert into test_data1 values(4,'wang',4);
3、查询表中数据,select * from test_data1;
4、编写目标sql;
select name,
max(case when day=1 then 1 end) d_1,
max(case when day=2 then 2 end) d_2,
max(case when day=3 then 3 end) d_3,
max(case when day=4 then 4 end) d_4
from test_data1 t group by name
mysql中,查询纵向转横向可用case when语句。
工具:mysql 5.6
步骤:
1、student表中有如下数据:
2、纵向显示每个班级的总分,用如下语句:
select class,sum(score) from student group by class;
查询结果:
3、要将结果横向显示,则用case when语句,语句如下:
select
sum(case when class='一年一班' then score else 0 end) 一年一班成绩,
sum(case when class='一年二班' then score else 0 end) 一年二班成绩,
sum(case when class='一年三班' then score else 0 end) 一年三班成绩
from student;
查询结果:
能说详细点吗,有点晕!
正常查询是“select * from table”;
要想横向显示“select * from table/G”
2011-05-30