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

นับจำนวนค่าซ้ำในคอลัมน์ MySQL และแสดงในคอลัมน์ใหม่

ใช้ COUNT() ร่วม GROUP BY แล้วต่อสตริงด้วย CONCAT()

ตัวอย่าง

mysql> create table DemoTable ( StudentFirstName varchar(20) );
Query OK, 0 rows affected (0.53 sec)
mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('John');  Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('David'); Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Bob');   Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('David'); Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.14 sec)

ข้อมูล

mysql> select * from DemoTable;
+------------------+
| StudentFirstName |
+------------------+
| Larry            |
| John             |
| Larry            |
| David            |
| Bob              |
| Larry            |
| David            |
| Larry            |
+------------------+

นับและแสดง

mysql> select StudentFirstName, concat(count(StudentFirstName),' times') from DemoTable group by StudentFirstName;
+------------------+------------------------------------------+
| StudentFirstName | concat(count(StudentFirstName),' times') |
+------------------+------------------------------------------+
| Larry            | 4 times                                  |
| John             | 1 times                                  |
| David            | 2 times                                  |
| Bob              | 1 times                                  |
+------------------+------------------------------------------+