
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement MySQL Conditional GROUP BY with NOT IN
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)
Advertisements