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

นับค่าที่ไม่ซ้ำในคอลัมน์ MySQL ด้วย GROUP BY

ใช้ COUNT(*) ร่วม GROUP BY เพื่อนับจำนวนแถวต่อแต่ละค่าที่ไม่ซ้ำ

ตัวอย่าง

mysql> create table DemoTable ( StudentFirstName varchar(20) );
Query OK, 0 rows affected (0.74 sec)
mysql> insert into DemoTable values('John');   Query OK, 1 row affected (1.34 sec)
mysql> insert into DemoTable values('Carol');  Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values('John');   Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('John');   Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Bob');    Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('David');  Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable values('Bob');    Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Carol');  Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.14 sec)

นับกลุ่ม

mysql> select StudentFirstName, count(*) from DemoTable group by StudentFirstName;
+------------------+----------+
| StudentFirstName | count(*) |
+------------------+----------+
| John             | 3        |
| Carol            | 2        |
| Bob              | 2        |
| David            | 1        |
| Robert           | 1        |
+------------------+----------+

นี่คือวิธีมาตรฐานในการได้ "Distinct count" ต่อกลุ่ม