How to determine if a value appears in a GROUP BY group in MySQL?


You can use aggregate function SUM() along with IF to determine if a value appears in a GROUP BY group.

Let us first create a demo table

mysql> create table GroupbygroupDemo
   -> (
   -> UserId int,
   -> UserName varchar(20)
   -> );
Query OK, 0 rows affected (1.48 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into GroupbygroupDemo values(10,'John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into GroupbygroupDemo values(10,'Carol');
Query OK, 1 row affected (0.08 sec)
mysql> insert into GroupbygroupDemo values(10,'Carol');
Query OK, 1 row affected (0.12 sec)
mysql> insert into GroupbygroupDemo values(20,'David');
Query OK, 1 row affected (0.17 sec)
mysql> insert into GroupbygroupDemo values(30,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into GroupbygroupDemo values(30,'David');
Query OK, 1 row affected (0.20 sec)
mysql> insert into GroupbygroupDemo values(30,'Mike');
Query OK, 1 row affected (0.16 sec)

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

mysql> select *from GroupbygroupDemo;

The output is as follows

+--------+----------+
| UserId | UserName |
+--------+----------+
|     10 | John     |
|     10 | Carol    |
|     10 | Carol    |
|     20 | David    |
|     30 | John     |
|     30 | David    |
|     30 | Mike     |
+--------+----------+
7 rows in set (0.00 sec)

Here is the query to determine if a value appears in a GROUP BY group

mysql> select UserId,
   -> if(sum(UserName='David'),'YES','NO') as Correct_Name_David
   -> from GroupbygroupDemo
   -> group by UserId;

The following is the output

+--------+--------------------+
| UserId | Correct_Name_David |
+--------+--------------------+
|     10 | NO                 |
|     20 | YES                |
|     30 | YES                |
+--------+--------------------+
3 rows in set (0.08 sec)

Updated on: 30-Jul-2019

476 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements