mysql横向转纵向、纵向转横向排列的方法

时间:2022-08-28 10:06:41

初始化数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
drop table if exists `test_01`;
create table `test_01` (
 `id` int(0) not null,
 `user` varchar(255) character set utf8mb4 collate utf8mb4_0900_ai_ci null default null comment '用户',
 `km` varchar(255) character set utf8mb4 collate utf8mb4_0900_ai_ci null default null comment '科目',
 `fs` varchar(255) character set utf8mb4 collate utf8mb4_0900_ai_ci null default null comment '分数',
 `time` datetime(0) null default null comment '时间',
 primary key (`id`) using btree
) engine = innodb character set = utf8mb4 collate = utf8mb4_0900_ai_ci row_format = dynamic;
 
insert into `test_01` values (1, '小三', '语文', '98', '2020-08-06 15:51:21');
insert into `test_01` values (2, '小三', '数学', '90', '2020-07-01 15:51:25');
insert into `test_01` values (3, '小三', '英语', '77', '2020-06-01 15:51:28');
insert into `test_01` values (4, '小二', '英语', '78', '2020-06-01 15:51:28');

一、横向转纵向排列

?
1
2
3
4
5
6
7
8
select
    user,
    sum( case when km = "语文" then fs else 0 end ) "语文",
    sum( case when km = "数学" then fs else 0 end ) "数学",
    sum( case when km = "英语" then fs else 0 end ) "英语"
from
    test_01
group by user

mysql横向转纵向、纵向转横向排列的方法

二、纵向转横向排列

?
1
2
3
select km from test_01 where id = 1
union
select fs from test_01 where id = 1

mysql横向转纵向、纵向转横向排列的方法

到此这篇关于mysql横向转纵向、纵向转横向排列的方法的文章就介绍到这了,更多相关mysql横向转纵向、纵向转横向排列内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_44325655/article/details/107841272