如何根據同名學生的成績快速地進行排序?
為此,請將 ORDER BY 與 GROUP BY 子句結合使用。讓我們首先建立一個包含學生姓名和分數的表格 −
mysql> create table countRowValueDemo -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentMathScore int -> ); Query OK, 0 rows affected (0.71 sec)
以下是使用 insert 命令向表中插入記錄的查詢 −
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Larry',45); Query OK, 1 row affected (0.19 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Mike',56); Query OK, 1 row affected (0.16 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',60); Query OK, 1 row affected (0.15 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',40); Query OK, 1 row affected (0.24 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',70); Query OK, 1 row affected (0.12 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',80); Query OK, 1 row affected (0.13 sec) mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',88); Query OK, 1 row affected (0.17 sec)
以下是使用 select 語句從表中顯示所有記錄的查詢 −
mysql> select * from countRowValueDemo;
這將生成以下輸出 −
+-----------+-------------+------------------+ | StudentId | StudentName | StudentMathScore | +-----------+-------------+------------------+ | 1 | Larry | 45 | | 2 | Mike | 56 | | 3 | John | 60 | | 4 | David | 40 | | 5 | David | 70 | | 6 | John | 80 | | 7 | David | 88 | +-----------+-------------+------------------+ 7 rows in set (0.00 sec)
案例 1:降序(總和)
以下是彙總具有相似名稱的學生分數的查詢。結果將按降序顯示 −
mysql> select StudentName, -> sum(StudentMathScore) AS TOTAL_SCORE -> from countRowValueDemo -> group by StudentName -> order by sum(StudentMathScore) desc;
這將生成以下輸出 −
+-------------+-------------+ | StudentName | TOTAL_SCORE | +-------------+-------------+ | David | 198 | | John | 140 | | Mike | 56 | | Larry | 45 | +-------------+-------------+ 4 rows in set (0.00 sec)
案例 2:升序(總和)
以下是對相似名稱的學生的分數進行求和的查詢。結果將按升序顯示 −
mysql> select StudentName, -> sum(StudentMathScore) AS TOTAL_SCORE -> from countRowValueDemo -> group by StudentName -> order by sum(StudentMathScore);
這將生成以下輸出 −
+-------------+-------------+ | StudentName | TOTAL_SCORE | +-------------+-------------+ | Larry | 45 | | Mike | 56 | | John | 140 | | David | 198 | +-------------+-------------+ 4 rows in set (0.00 sec)
廣告