SQL Aggregate Concatenate

Sometimes it is required to combine the result set of records from different fields.

SQL Aggregate Concatenate

SQL Aggregate Concatenate

     

Sometimes it is required to combine the result set of  records from different fields. The database provides you the solution to concatenate this different field. The Syntax given below helps you to concatenate different fields in Mysql :

concat ( ): The Syntax is used to combine the result set from different fields name.

Understand with Example

To understand SQL Aggregate Concatenate, the Tutorial provides you an elaborate example on it. The create table is used to create a table Stu with specified fieldnames and datatypes required.  

 

 

Create Table Stu:

create table Stu(Id varchar(2), Name varchar(15), 
Class  varchar(10),sub_id varchar(2),marks varchar(3));

Insert data into Stu:

The insert into add the records or rows to the table 'Stu'.

insert into Stu values(1,'Komal',10,1,45);
insert into Stu values(2,'Ajay',10,1,56);
insert into Stu values(3,'Rakesh',10,1,67);
insert into Stu values(4,'Santosh',10,1,67);
insert into Stu values(1,'Komal',10,2,47);
insert into Stu values(2,'Ajay',10,2,53);
insert into Stu values(3,'Rakesh',10,2,57);
insert into Stu values(4,'Santosh',10,2,67);
insert into Stu values(5,'Bhanu',10,2,67);
insert into Stu values(1,'Komal',10,3,45);
insert into Stu values(2,'Ajay',10,3,56);
insert into Stu values(3,'Rakesh',10,3,67);
insert into Stu values(4,'Santosh',10,3,67);
insert into Stu values(5,'Bhanu',10,3,67);
insert into Stu values(1,'Komal',10,4,65);
insert into Stu values(2,'Ajay',10,4,56);
insert into Stu values(3,'Rakesh',10,4,37);
insert into Stu values(4,'Santosh',10,4,67);
insert into Stu values(5,'Bhanu',10,2,67);
insert into Stu values(1,'Komal',10,5,65);
insert into Stu values(2,'Ajay',10,5,46);
insert into Stu values(3,'Rakesh',10,5,63);

Concatenate Functions:

The Syntax Group _Concat(marks order by sub_id) returns the combine set of records in ascending order id. The Group by keyword is used when we are performing queries on multiple columns from a table.

mysql> select id, name, GROUP_CONCAT(marks order by sub_id)
    -> from stu  group by id;
+------+---------+-------------------------------------+
| id   | name    | GROUP_CONCAT(marks order by sub_id) |
+------+---------+-------------------------------------+
| 1    | Komal   | 45,47,45,65,65                      |
| 2    | Ajay    | 56,53,56,56,46                      |
| 3    | Rakesh  | 67,57,67,37,63                      |
| 4    | Santosh | 67,67,67,67                         |
| 5    | Bhanu   | 67,67,67                            |
+------+---------+-------------------------------------+
5 rows in set (0.00 sec)