Listing all rows by group with MySQL GROUP BY?

MySQLMySQLi Database

To list all rows by group, you can use GROUP_CONCAT(). Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20),
   Value varchar(100)
   );
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name,Value) values('John','John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name,Value) values('Carol','Carol');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(Name,Value) values('John','Works');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Name,Value) values('Carol','Works');
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable(Name,Value) values('John','At');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name,Value) values('Carol','At');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Name,Value) values('John','Amazon');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name,Value) values('Carol','Google');
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 -

+----+-------+--------+
| Id | Name  | Value  |
+----+-------+--------+
| 1  | John  | John   |
| 2  | Carol | Carol  |
| 3  | John  | Works  |
| 4  | Carol | Works  |
| 5  | John  | At     |
| 6  | Carol | At     |
| 7  | John  | Amazon |
| 8  | Carol | Google |
+----+-------+--------+
8 rows in set (0.00 sec)

Following is the query to list all rows by group. Here value for ‘John’ would be fetched i.e. “John Works At Amazon from id 1, 3, 5, 7. In the same way, it would work for ‘Carol’ −

mysql> select Name, GROUP_CONCAT(Value SEPARATOR ' ') AS `Complete_Status` from DemoTable group by Name;

This will produce the following output −

+-------+-----------------------+
| Name  | Complete_Status       |
+-------+-----------------------+
| Carol | Carol Works At Google |
| John  | John Works At Amazon  | 
+-------+-----------------------+
2 rows in set (0.00 sec)
raja
Published on 20-May-2019 16:36:05
Advertisements