话不多说, 先看数据表信息.
假设在某次期末考试中,二年级四个班的平均成绩分别是 93、93、93、91。
+-------+-----------+
| class | score_avg |
+-------+-----------+
| 1 | 93 |
| 2 | 93 |
| 3 | 93 |
| 4 | 91 |
+-------+-----------+
话不多说, 再看需求~
目前有如下三种排序结果,请根据查询结果书写出查询用 sql .
+-------+-----------+-------+-------+-------+
| class | score_avg | rank1 | rank2 | rank3 |
+-------+-----------+-------+-------+-------+
| 1 | 93 | 1 | 1 | 1 |
| 2 | 93 | 1 | 1 | 2 |
| 3 | 93 | 1 | 1 | 3 |
| 4 | 91 | 4 | 2 | 4 |
+-------+-----------+-------+-------+-------+
话不多说, 进行拆解~
其实, 这里根据三种排序的规则的话, 可以看出这里主要是考察的是排序类窗口函数.
正好, 根据这个题目, 大家可以再加深或者学习一下三者的使用方法和异同点.
话不多说, 直接SQL~
select
class,
score_avg,
rank() over(order by score_avg desc) as rank1,
dense_rank() over(order by score_avg desc) as rank2,
row_number() over(order by score_avg desc) as rank3
from score
;
大家如果还想进一步学习一些不同的排序类窗口函数, 可以参考如下文章:
最后给大家介绍一下我这边的操作步骤, 想要自己测试的话, 可以参考:
mysql> CREATE TABLE score (
-> class INT,
-> score_avg INT
-> );
Query OK, 0 rows affected (0.04 sec)
mysql> show tables;
+-------------------------+
| Tables_in_test_study_db |
+-------------------------+
| aaa |
| ceshi |
| my_table |
| score |
| table_a |
+-------------------------+
5 rows in set (0.00 sec)
mysql> INSERT INTO score (class, score_avg)
-> VALUES (1, 93), (2, 93), (3, 93), (4, 91);
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from score;
+-------+-----------+
| class | score_avg |
+-------+-----------+
| 1 | 93 |
| 2 | 93 |
| 3 | 93 |
| 4 | 91 |
+-------+-----------+
4 rows in set (0.00 sec)
mysql>