Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธีใช้ฟังก์ชันกลุ่มในคำสั่ง ORDER BY ของ MySQL


สามารถจัดเรียงกลุ่มผลลัพธ์โดยใช้ฟังก์ชันกลุ่มในคำสั่ง ORDER BY โดยค่าเริ่มต้นเป็นลำดับจากน้อยไปมาก (ASC) แต่สามารถกลับลำดับได้ด้วยคำสั่ง 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)

สรุป: ตัวอย่างแรกจัดเรียงตามจำนวนนับ (count) มากไปน้อย ตัวอย่างที่สองจัดเรียงตามชื่อตำแหน่ง (designation) จาก Z ไป A