- CREATE TABLE `t_score` (
- `id` int NOT NULL AUTO_INCREMENT,
- `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '姓名',
- `sex` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '性别',
- `score` double(20, 2) NULL DEFAULT NULL COMMENT '成绩',
- `subject` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '科目',
- `create_time` datetime NULL DEFAULT NULL,
- `update_time` datetime NULL DEFAULT NULL,
- PRIMARY KEY (`id`) USING BTREE
- ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
- INSERT INTO `t_score` VALUES (1, '张三', '男', 63.00, '语文', '2023-09-06 10:06:22', '2023-09-26 10:06:25');
- INSERT INTO `t_score` VALUES (2, '李四', '男', 75.00, '语文', '2023-09-26 10:06:32', '2023-09-26 10:06:36');
- INSERT INTO `t_score` VALUES (3, '小美', '女', 89.00, '语文', '2023-09-26 10:06:46', '2023-09-26 10:06:48');
- INSERT INTO `t_score` VALUES (4, '张三', '男', 78.00, '数学', '2023-09-06 10:06:22', '2023-09-26 10:06:25');
- INSERT INTO `t_score` VALUES (5, '李四', '男', 79.00, '数学', '2023-09-26 10:06:32', '2023-09-26 10:06:36');
- INSERT INTO `t_score` VALUES (6, '小美', '女', 94.00, '数学', '2023-09-26 10:06:46', '2023-09-26 10:06:48');
- INSERT INTO `t_score` VALUES (7, '张三', '男', 45.00, '英语', '2023-09-06 10:06:22', '2023-09-26 10:06:25');
- INSERT INTO `t_score` VALUES (8, '李四', '男', 34.00, '英语', '2023-09-26 10:06:32', '2023-09-26 10:06:36');
- INSERT INTO `t_score` VALUES (9, '小美', '女', 99.00, '英语', '2023-09-26 10:06:46', '2023-09-26 10:06:48');
- SELECT
- id,
- `name`,
- `score`,
- `subject`,
- ROW_NUMBER()OVER(PARTITION BY `name` ORDER BY `SCORE` DESC) AS row_index
- FROM t_score;
效果:
- SELECT *
- FROM(
- SELECT
- id,
- `name`,
- `score`,
- `subject`,
- ROW_NUMBER()OVER(PARTITION BY `name` ORDER BY `SCORE` DESC) AS row_index
- FROM t_score) AS ib
- WHERE ib.row_index = 1;