mysql 行转列和列转行实例详解
程序员文章站
2023-11-22 12:10:52
mysql行转列、列转行
语句不难,不做多余解释了,看语句时,从内往外一句一句剖析
行转列
&...
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', primary key (`id`) ) engine=innodb auto_increment=1 default charset=utf8;
insert into test_tb_grade(user_name, course, score) values ("张三", "数学", 34), ("张三", "语文", 58), ("张三", "英语", 58), ("李四", "数学", 45), ("李四", "语文", 87), ("李四", "英语", 45), ("王五", "数学", 76), ("王五", "语文", 34), ("王五", "英语", 89);
查询语句:
此处用之所以用max是为了将无数据的点设为0,防止出现null
select user_name , 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 ) 英语 from test_tb_grade group by user_name;
结果展示:
列转行
有如图所示的表,现在希望查询的结果将列成行
建表语句如下:
create table `test_tb_grade2` ( `id` int(10) not null auto_increment, `user_name` varchar(20) default null, `cn_score` float default null, `math_score` float default null, `en_score` float default '0', primary key (`id`) ) engine=innodb auto_increment=1 default charset=utf8;
insert into test_tb_grade2(user_name, cn_score, math_score, en_score) values ("张三", 34, 58, 58), ("李四", 45, 87, 45), ("王五", 76, 34, 89);
查询语句:
select user_name, '语文' course , cn_score as score from test_tb_grade2 union select user_name, '数学' course, math_score as score from test_tb_grade2 union select user_name, '英语' course, en_score as score from test_tb_grade2 order by user_name,course;
结果展示:
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!