
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
MySQL GROUP BY and CONCAT to Display Distinct First and Last Name
Let us first create a table −
mysql> create table DemoTable ( FirstName varchar(100), LastName varchar(100) ); Query OK, 0 rows affected (0.92 sec) mysql> alter table DemoTable add index(FirstName,LastName); Query OK, 0 rows affected (1.00 sec) Records: 0 Duplicates: 0 Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Adam','Smith'); Query OK, 1 row affected (0.73 sec) mysql> insert into DemoTable values('Adam','Smith'); Query OK, 1 row affected (1.17 sec) mysql> insert into DemoTable values('John','Doe'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('Carol','Taylor'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('John','Doe'); Query OK, 1 row affected (0.66 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | Adam | Smith | | Adam | Smith | | Carol | Taylor | | John | Doe | | John | Doe | +-----------+----------+ 5 rows in set (0.00 sec)
Following is the query to combine distinct First and Last Name −
mysql> select concat(FirstName,' ',LastName) as combinedName from DemoTable group by LastName,FirstName;
This will produce the following output −
+--------------+ | combinedName | +--------------+ | Adam Smith | | Carol Taylor | | John Doe | +--------------+ 3 rows in set (0.00 sec)
Advertisements