服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Mysql - mysql横向转纵向、纵向转横向排列的方法

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

2021-02-26 17:37姚鑫国 Mysql

这篇文章主要介绍了mysql横向转纵向、纵向转横向排列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

初始化数据

?
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

延伸 · 阅读

精彩推荐