Mysql 开窗函数实战
Mysql 开窗函数实战
Mysql 开窗函数在Mysql8.0+ 中可以得以使用,实在且好用。
- row number() over
- rank() over
- dense rank()
- ntile()
我们先上测试数据,是不同姓名,不同课程的分数表;
/*测试数据*/ CREATE TABLE `school_score` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` char(1) DEFAULT NULL, `course` char(10) DEFAULT NULL, `score` int (2) DEFAULT NULL, PRIMARY KEY (`id`) ) ; INSERT INTO `test`.`school_score`(`id`, `name`,`course`,`score`) VALUES (1, \'A\',\'Chinese\',80); INSERT INTO `test`.`school_score`(`id`, `name`,`course`,`score`) VALUES (2, \'B\',\'Chinese\',90); INSERT INTO `test`.`school_score`(`id`, `name`,`course`,`score`) VALUES (3, \'C\',\'Chinese\',70); INSERT INTO `test`.`school_score`(`id`, `name`,`course`,`score`) VALUES (4, \'A\',\'Math\',70); INSERT INTO `test`.`school_score`(`id`, `name`,`course`,`score`) VALUES (5, \'B\',\'Math\',100); INSERT INTO `test`.`school_score`(`id`, `name`,`course`,`score`) VALUES (6, \'C\',\'Math\',80); INSERT INTO `test`.`school_score`(`id`, `name`,`course`,`score`) VALUES (7, \'A\',\'English\',90); INSERT INTO `test`.`school_score`(`id`, `name`,`course`,`score`) VALUES (8, \'B\',\'English\',85); INSERT INTO `test`.`school_score` (`id`, `name`,`course`,`score`) VALUES (9, \'C\',\'English\',99);
- row number() over
/*开窗函数和排名类函数结合,看每个课程的排名*/ SELECT `name`, `course`, `score`, row_number ( ) over ( PARTITION BY `course` ORDER BY score DESC ) AS score_rank FROM `test`.`school_score`;
结果