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

การนับจำนวนข้อมูลซ้ำและเรียงลำดับผลลัพธ์ใน MySQL

เพื่อนับจำนวนข้อมูลที่ซ้ำกันในคอลัมน์และเรียงลำดับผลลัพธ์ ใช้ GROUP BY ร่วมกับ COUNT(*) และ ORDER BY

รูปแบบคำสั่ง (Syntax)

select count(*) as anyAliasName from yourTableName group by yourColumnName order By yourAliasName DESC;

สร้างตารางตัวอย่าง

mysql> create table DemoTable ( 
    Number int ); 
Query OK, 0 rows affected (0.82 sec)

เพิ่มข้อมูลตัวอย่าง (มีค่าซ้ำ)

mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(110); Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(120); Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(120); Query OK, 1 row affected (0.13 sec)

แสดงข้อมูลทั้งหมด

mysql> select *from DemoTable;
+--------+
| Number |
+--------+
|     90 |
|    100 |
|    110 |
|     90 |
|    100 |
|     90 |
|    120 |
|    100 |
|     90 |
|    120 |
+--------+
10 rows in set (0.00 sec)

คิวรี่นับจำนวนซ้ำและเรียงลำดับมากไปน้อย

mysql> select count(*) as Occured from DemoTable group by Number order By Occured DESC;

ผลลัพธ์:

+---------+
| Occured |
+---------+
|       4 |
|       3 |
|       2 |
|       1 |
+---------+
4 rows in set (0.00 sec)

คำอธิบายเพิ่มเติม

  • GROUP BY Number จัดกลุ่มค่า 90, 100, 110, 120 แยกกัน
  • COUNT(*) นับจำนวนแถวในแต่ละกลุ่ม
  • ORDER BY Occured DESC เรียงจากจำนวนมากไปน้อย
  • หากต้องการแสดงค่าที่ซ้ำพร้อมกับจำนวน ใช้ SELECT Number, COUNT(*) as Occured ...