
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
Distinct Number of Specific Items in List with MySQL
To find distinct number of specific items, use COUNT() along with GROUP BY clause. Let us first create a table −
mysql> create table DemoTable1854 ( Name varchar(20) ); Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1854 values('John-Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1854 values('Chris-Brown'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1854 values('Adam-Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1854 values('John-Doe'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1854 values('John-Smith'); Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1854;
This will produce the following output −
+-------------+ | Name | +-------------+ | John-Smith | | Chris-Brown | | Adam-Smith | | John-Doe | | John-Smith | +-------------+ 5 rows in set (0.00 sec)
Here is the query to get the distinct number of specific items in list −
mysql> select Name,count(Name) from DemoTable1854 where Name like 'John-%' group by Name;
This will produce the following output −
+------------+-------------+ | Name | count(Name) | +------------+-------------+ | John-Smith | 2 | | John-Doe | 1 | +------------+-------------+ 2 rows in set (0.00 sec)
Advertisements