MySQL query to find the number of occurrences from two columns?


Use MySQL GROUP_BY to find the number of occurrences from two columns. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name1 varchar(20),
   -> Name2 varchar(20)
   -> );
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John','Adam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Chris','David');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Robert','Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('David','Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Mike','Robert');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+--------+
| Name1  | Name2  |
+--------+--------+
| John   | Adam   |
| Chris  | David  |
| Robert | Mike   |
| David  | Chris  |
| Mike   | Robert |
+--------+--------+
5 rows in set (0.00 sec)

Here is the query to find the number of occurrences from two columns −

mysql> select greatest(Name1,Name2),least(Name1,Name2),count(*) as Occurrences from DemoTable
   -> group by greatest(Name1,Name2),least(Name1,Name2);

This will produce the following output −

+-----------------------+--------------------+-------------+
| greatest(Name1,Name2) | least(Name1,Name2) | Occurrences |
+-----------------------+--------------------+-------------+
| John                  | Adam               |           1 |
| David                 | Chris              |           2 |
| Robert                | Mike               |           2 |
+-----------------------+--------------------+-------------+
3 rows in set (0.02 sec)

Updated on: 13-Dec-2019

350 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements