Counting same strings in a new MySQL column?

MySQLMySQLi Database

Use COUNT() for this. Let us first create a table −

mysql> create table DemoTable
   (
   StudentFirstName varchar(20)
   );
Query OK, 0 rows affected (0.53 sec)

Insert records in the table using insert command −

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)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+------------------+
| StudentFirstName |
+------------------+
| Larry            |
| John             |
| Larry            |
| David            |
| Bob              |
| Larry            |
| David            |
| Larry            |
+------------------+
8 rows in set (0.00 sec)

Following is the query to count same strings in MySQL −

mysql> select StudentFirstName,concat(count(StudentFirstName),' times') from DemoTable
group by StudentFirstName;

This will produce the following output −

+------------------+------------------------------------------+
| StudentFirstName | concat(count(StudentFirstName),' times') |
+------------------+------------------------------------------+
| Larry            | 4 times                                  |
| John             | 1 times                                  |
| David            | 2 times                                  |
| Bob              | 1 times                                  |
+------------------+------------------------------------------+
4 rows in set (0.00 sec)
raja
Published on 03-May-2019 12:09:57
Advertisements