如何將組函式與 ORDER BY 子句配合使用?


我們可以利用 ORDER BY 子句中的組函式對結果集組進行排序。預設情況下,排序順序是升序,但我們可以使用 DESC 關鍵字來反轉它。

示例

mysql> Select designation, YEAR(Doj), count(*) from employees GROUP BY designation, YEAR(DoJ) ORDER BY Count(*) DESC;
+-------------+-----------+----------+
| designation | YEAR(Doj) | count(*) |
+-------------+-----------+----------+
| Prof        |      2009 |        2 |
| Asst.Prof   |      2015 |        1 |
| Asst.Prof   |      2016 |        1 |
| Prof        |      2010 |        1 |
| Asso.Prof   |      2013 |        1 |
+-------------+-----------+----------+
5 rows in set (0.00 sec)

mysql> Select designation, YEAR(Doj), count(*) from employees GROUP BY designation, YEAR(DoJ) ORDER BY designation DESC;
+-------------+-----------+----------+
| designation | YEAR(Doj) | count(*) |
+-------------+-----------+----------+
| Prof        |      2009 |        2 |
| Prof        |      2010 |        1 |
| Asst.Prof   |      2015 |        1 |
| Asst.Prof   |      2016 |        1 |
| Asso.Prof   |      2013 |        1 |
+-------------+-----------+----------+
5 rows in set (0.00 sec)

更新日期:2020-06-22

114 次瀏覽

開啟你的 職業

完成課程取得認證

開始吧
廣告
© . All rights reserved.