1.行轉列
有如圖所示的表,現在希望查詢的結果將行轉成列(語文,數學,英文變成列):
使用如下查詢語句實現行轉列:
select id,name, max(case when course = '語文' then score else 0 end) '語文' , max(case when course = '數學' then score else 0 end) '數學' , max(case when course = '英語' then score else 0 end) '英語' from student group by id,name
效果如下:
2.列轉行
有如圖所示的表,現在希望查詢的結果將列成行
使用如下查詢語句實現列轉行:
select id, name, '語文' as 'scrore' from student2 union select id, name, '數學' as 'scrore' from student2 union select id, name, '英語' as 'scrore' from student2
效果如下:
所需表和資料如下:
drop table if exists `student`;
create table `student` (
`id` varchar(255) character set utf8 collate utf8_general_ci not null,
`name` varchar(255) character set utf8 collate utf8_general_ci null default null,
`score` int(40) null default null,
`course` varchar(255) character set utf8 collate utf8_general_ci null default null
) engine = innodb character set = utf8 collate = utf8_general_ci row_format = dynamic;
insert into `student` values ('12', 'tbb', 80, '語文');
insert into `student` values ('12', 'tbb', 70, '數學');
insert into `student` values ('12', 'tbb', 60, '英語');
insert into `student` values ('13', 'xb', 98, '語文');
insert into `student` values ('13', 'xb', 96, '英語');
insert into `student` values ('13', 'xb', 97, '數學');
insert into `student` values ('14', 'xz', 18, '語文');
insert into `student` values ('14', 'xz', 28, '數學');
insert into `student` values ('14', 'xz', 8, '英語');
drop table if exists `student2`;
create table `student2` (
`id` int(11) not null,
`name` varchar(255) character set utf8 collate utf8_general_ci null default null,
`語文` int(40) null default null,
`數學` int(40) null default null,
`英語` int(40) null default null
) engine = innodb character set = utf8 collate = utf8_general_ci row_format = dynamic;
insert into `student2` values (12, 'tbb', 78, 77, 76);
insert into `student2` values (13, 'xm', 90, 91, 92);
insert into `student2` values (14, 'xz', 32, 31, 30);
Mysql 行轉列 列轉行
create table test tb grade id int 10 not null auto increment,user name varchar 20 default null,course varchar 20 default null,score float default 0 pr...
MySQL行轉列 列轉行
max case course when 數學 then score else 0 end 數學,max case course when 語文 then score else 0 end 語文,max case course when 英語 then score else 0 end 英語 fro...
MySQL 行轉列 列轉行
以下內容包括 行轉列 sql 執行效果展示 列轉行 sql 執行效果展示 總結 附上的建表語句 一 行轉列 廢話不多說,先上sql 兩種方式 行轉列 方法 select id,name,group concat case when subject 語文 then score end separato...