mysql row to column column to row

Left to right effect
insert image description here

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50618
Source Host           : 127.0.0.1:3306
Source Database       : sadsadsad

Target Server Type    : MYSQL
Target Server Version : 50618
File Encoding         : 65001

Date: 2020-03-18 11:11:53
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for score1
-- ----------------------------
DROP TABLE IF EXISTS `score1`;
CREATE TABLE `score1` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `USER_NAME` varchar(255) DEFAULT NULL,
  `COURSE` varchar(255) DEFAULT NULL,
  `SCORE` int(11) DEFAULT NULL,
  `AGE` int(2) DEFAULT NULL,
	`PHONE` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of score1
-- ----------------------------
INSERT INTO `score1` VALUES ('1', '李四', '数学', '34','20','13311111111');
INSERT INTO `score1` VALUES ('2', '王五', '语文', '58','21','13322222222');
INSERT INTO `score1` VALUES ('3', '张三', '英语', '58','22','13333333333');
INSERT INTO `score1` VALUES ('4', '王五', '数学', '45','23','13344444444');
INSERT INTO `score1` VALUES ('5', '张三', '语文', '87','24','13355555555');
INSERT INTO `score1` VALUES ('6', '李四', '英语', '45','25','13366666666');
INSERT INTO `score1` VALUES ('7', '张三', '数学', '76','26','13377777777');
INSERT INTO `score1` VALUES ('8', '李四', '语文', '34','27','13388888888');
INSERT INTO `score1` VALUES ('9', '王五', '英语', '89','28','13399999999');

//查询效果
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 score1 GROUP BY USER_NAME

Guess you like

Origin blog.csdn.net/m0_54850604/article/details/123627373