1. 初始化
CREATE TABLE `tb_score` (
`score_id` bigint unsigned NOT NULL AUTO_INCREMENT,
`course` varchar(64) DEFAULT NULL COMMENT '课程',
`score` decimal(10,2) DEFAULT NULL,
`user_name` varchar(64) DEFAULT NULL COMMENT '用户姓名',
PRIMARY KEY (`score_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `tb_score` (`score_id`, `course`, `score`, `user_name`) VALUES (1, '语文', 89.00, '张三');
INSERT INTO `tb_score` (`score_id`, `course`, `score`, `user_name`) VALUES (2, '数学', 99.00, '张三');
INSERT INTO `tb_score` (`score_id`, `course`, `score`, `user_name`) VALUES (3, '物理', 95.00, '张三');
INSERT INTO `tb_score` (`score_id`, `course`, `score`, `user_name`) VALUES (4, '语文', 78.00, '李四');
INSERT INTO `tb_score` (`score_id`, `course`, `score`, `user_name`) VALUES (5, '数学', 94.00, '李四');
INSERT INTO `tb_score` (`score_id`, `course`, `score`, `user_name`) VALUES (6, '物理', 100.00, '李四');
2. 数据
3. 要求
查出每个人最大的成绩的课程名称。
4. SQL
SELECT
SUBSTRING_INDEX( GROUP_CONCAT( score_id ORDER BY score DESC SEPARATOR ";" ), ";", 1 ) AS scoreId,
SUBSTRING_INDEX( GROUP_CONCAT( user_name ORDER BY score DESC SEPARATOR ";" ), ";", 1 ) AS userName,
SUBSTRING_INDEX( GROUP_CONCAT( course ORDER BY score DESC SEPARATOR ";" ), ";", 1 ) AS course,
SUBSTRING_INDEX( GROUP_CONCAT( score ORDER BY score DESC SEPARATOR ";" ), ";", 1 ) AS score
FROM
tb_score
GROUP BY
user_name