Display duplicate record as a distinct value with corresponding values as distinct comma separated list in MySQL?

MySQLMySQLi Database

For this, you can use GROUP_CONCAT(). You also need to use DISTINCT to fetch distinct records. Let us first create a table −

mysql> create table DemoTable(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(40),
   Score int
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name,Score) values('Chris',56);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name,Score) values('Robert',78);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name,Score) values('Chris',56);
Query OK, 1 row affected (0.42 sec)
mysql> insert into DemoTable(Name,Score) values('Bob',89);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Score) values('Chris',56);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(Name,Score) values('Chris',57);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output. Here, we have repeated “Name” records with duplicate “Score” values −

+----+--------+-------+
| Id | Name   | Score |
+----+--------+-------+
|  1 | Chris  |    56 |
|  2 | Robert |    78 |
|  3 | Chris  |    56 |
|  4 | Bob    |    89 |
|  5 | Chris  |    56 |
|  6 | Chris  |    57 |
+----+--------+-------+
6 rows in set (0.00 sec)

Following is the query to loop record from the table which already uses GROUP BY −

mysql> select Name, group_concat(DISTINCT Score separator ',') from DemoTable group by Name;

This will produce the following output −

+--------+--------------------------------------------+
| Name   | group_concat(DISTINCT Score separator ',') |
+--------+--------------------------------------------+
| Bob    | 89                                         |
| Chris  | 56,57                                      |
| Robert | 78                                         |
+--------+--------------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 04-Oct-2019 11:15:49
Advertisements