A single MySQL query to combine strings from many rows into a single row and display the corresponding User Id sum in another column?


For this, you can use GROUP_CONCAT(). Use SUM() to add the User Id. Let us first create a table −

mysql> create table DemoTable1960
   (
   StudentId int,
   StudentName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1960 values(100,'Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1960 values(101,'Bob');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1960 values(102,'David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1960 values(103,'Mike');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1960;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       100 | Chris       |
|       101 | Bob         |
|       102 | David       |
|       103 | Mike        |
+-----------+-------------+
4 rows in set (0.00 sec)

Here is the query to combine strings from many rows into a single row and also display the sum of User Ids −

mysql> select sum(StudentId),group_concat(StudentName separator '.') as ListOfStudent from DemoTable1960;

This will produce the following output −

+----------------+----------------------+
| sum(StudentId) | ListOfStudent        |
+----------------+----------------------+
|            406 | Chris.Bob.David.Mike |
+----------------+----------------------+
1 row in set (0.00 sec)

Updated on: 31-Dec-2019

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements