MySQL8.0之前,做數(shù)據(jù)排名統(tǒng)計等相當痛苦,因為沒有像Oracle、SQL SERVER 、PostgreSQL等其他數(shù)據(jù)庫那樣的窗口函數(shù)。但隨著MySQL8.0中新增了窗口函數(shù)之后,針對這類統(tǒng)計就再也不是事了,本文就以常用的排序實例介紹MySQL的窗口函數(shù)。
mysql> use testdb;
Database changed
/* 創(chuàng)建表 */
mysql> create table tb_score(id int primary key auto_increment,stu_no varchar(10),course varchar(50),score decimal(4,1),key idx_stuNo_course(stu_no,course));
Query OK, 0 rows affected (0.03 sec)
mysql> show tables;
+------------------+
| Tables_in_testdb |
+------------------+
| tb_score |
+------------------+
/* 新增一批測試數(shù)據(jù) */
mysql> insert into tb_score(stu_no,course,score)values('2020001','mysql',90),('2020001','C++',85),('2020003','English',100),('2020002','mysql',50),('2020002','C++',70),('2020002','English',99);
Query OK, 6 rows affected (0.00 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> insert into tb_score(stu_no,course,score)values('2020003','mysql',78),('2020003','C++',81),('2020003','English',80),('2020004','mysql',80),('2020004','C++',60),('2020004','English',100);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> insert into tb_score(stu_no,course,score)values('2020005','mysql',98),('2020005','C++',96),('2020005','English',70),('2020006','mysql',60),('2020006','C++',90),('2020006','English',70);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> insert into tb_score(stu_no,course,score)values('2020007','mysql',50),('2020007','C++',66),('2020007','English',76),('2020008','mysql',90),('2020008','C++',69),('2020008','English',86);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> insert into tb_score(stu_no,course,score)values('2020009','mysql',70),('2020009','C++',66),('2020009','English',86),('2020010','mysql',75),('2020010','C++',76),('2020010','English',81);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> insert into tb_score(stu_no,course,score)values('2020011','mysql',90),('2020012','C++',85),('2020011','English',84),('2020012','English',75),('2020013','C++',96),('2020013','English',88);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
根據(jù)每門課程的分數(shù)從高到低進行排名,此時,會出現(xiàn)分數(shù)相同時怎么處理的問題,下面就根據(jù)不同的窗口函數(shù)來處理不同場景的需求
DENSE_RANK的結果是分數(shù)相同時排名相同了,但是下一個名次是緊接著上一個名次的,如果2個并列的第1之后,下一個我想是第3名,則可以使用RANK函數(shù)實現(xiàn)
MySQL中主要的窗口函數(shù)先總結這么多,建議還是得動手實踐一番。另外,MySQL5.7及之前版本的排序方式的實現(xiàn)很多人已總結,也建議實操一番。
到此這篇關于MySQL8.0窗口函數(shù)入門實踐及總結的文章就介紹到這了,更多相關MySQL8.0窗口函數(shù)實踐內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!