Count multiple occurrences of separate texts in MySQL?

MySQLMySQLi Database

You can use aggregate function count along with if() for this. To understand the concept, let us create a table. The query to create a table is as follows

mysql> create table CountOccurrencesDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> TechnicalSubject varchar(100)
   -> );
Query OK, 0 rows affected (0.68 sec)

Now you can insert some records in the table using insert command. The query is as follows

mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.14 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MongoDB');
Query OK, 1 row affected (0.13 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MySQL');
Query OK, 1 row affected (0.16 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MySQL');
Query OK, 1 row affected (0.10 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MySQL');
Query OK, 1 row affected (0.07 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.15 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.10 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.09 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('Java');
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountOccurrencesDemo(TechnicalSubject) values('MongoDB');
Query OK, 1 row affected (0.21 sec)

Display all records from the table using a select statement. The query is as follows

mysql> select *from CountOccurrencesDemo;

The following is the output

+----+------------------+
| Id | TechnicalSubject |
+----+------------------+
| 1  | Java             |
| 2  | MongoDB          |
| 3  | MySQL            |
| 4  | MySQL            |
| 5  | MySQL            |
| 6  | Java             |
| 7  | Java             |
| 8  | Java             |
| 9  | Java             |
| 10 | MongoDB          |
+----+------------------+
10 rows in set (0.00 sec)

The following is the query to count multiple occurrences of text in MySQL

mysql> select count(if(tbl.TechnicalSubject LIKE '%Java%',1,null)) as JavaOccurrence,
   -> count(if(tbl.TechnicalSubject LIKE '%MySQL%',1,null)) as MySQLOccurrence,
   -> count(if(tbl.TechnicalSubject LIKE '%MongoDB%',1,null)) as MongoDBOccurrence
   -> from CountOccurrencesDemo tbl;

The following is the output

+----------------+-----------------+-------------------+
| JavaOccurrence | MySQLOccurrence | MongoDBOccurrence |
+----------------+-----------------+-------------------+
| 5              | 3               | 2                 |
+----------------+-----------------+-------------------+
1 row in set (0.05 sec)
raja
Published on 20-Mar-2019 10:16:56
Advertisements