MySQL分組查詢獲取每一個學生前n條分數記錄(分組查詢前n條記錄)

CREATE TABLE `t_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stuid` varchar(36) NOT NULL,
  `score` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('1', '111', '90');
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('2', '111', '11');
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('3', '111', '34');
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('4', '111', '99');
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('5', '222', '11');
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('6', '222', '33');
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('7', '222', '41');
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('8', '333', '123');
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('9', '333', '100');
INSERT INTO `testdb`.`t_test` (`id`, `stuid`, `score`) VALUES ('10', '333', '99');

測試數據測試

SELECT *,
(SELECT count(id) FROM t_test t2
where t1.stuid=t2.stuid AND 
t2.score>t1.score -- 獲取t2大於t1的記錄數
)as maxcnt
 from t_test t1

到這一步就很簡單了.其實只要根據狀況取macnt的數據就好了,若是要取前2條,那麼篩選maxcnt<2的數據便可.ui

(如111學生大於99的有0條,大於90的有1條,大於34的有2條,那麼要取最高分的前3條,就是maxcnt<3)spa

SELECT *
 FROM t_test t1
WHERE
(
SELECT count(id) FROM t_test t2
where t2.stuid=t1.stuid and t2.score>t1.score
)<3
ORDER BY stuid asc,score DESC

效果圖code

相關文章
相關標籤/搜索