1. 个人技术分享首页

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

初始化数据

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');

一、横向转纵向排列

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横向转纵向、纵向转横向排列的方法

二、纵向转横向排列

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

文章来源于互联网:mysql横向转纵向、纵向转横向排列的方法

原创文章,作者:admin,如若转载,请注明出处:https://www.aliyunsolution.com/3202.html