Implement MySQL conditional GROUP BY with NOT IN to filter records from duplicate column values

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   Name varchar(40),
   Score int
);
Query OK, 0 rows affected (0.48 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Adam',89);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Adam',89);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Chris',89);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Chris',89);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Bob',98);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Bob',89);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+-------+
| Name  | Score |
+-------+-------+
| Adam  |    89 |
| Adam  |    89 |
| Chris |    89 |
| Chris |    89 |
| Bob   |    98 |
| Bob   |    89 |
+-------+-------+
6 rows in set (0.00 sec)

Following is the query to achieve conditional GROUP BY using NOT IN() −

mysql> select distinct Name from DemoTable where Name
not in(select Name from DemoTable where Score <> 89);

This will produce the following output −

+-------+
| Name  |
+-------+
| Adam  |
| Chris |
+-------+q
2 rows in set (0.06 sec)
raja
Published on 04-Oct-2019 10:03:23
Advertisements