Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat all values of single column in mysql

Tags:

mysql

I have column A in the Sample Table1. Column A has values as follows.

+----+
| A  |
+----+
| a1 |
| a2 |
| a3 |
| a4 |
| a5 |
+----+

I need a query that should give the following output. All the Values should be

"a1","a2","a3","a4","a5"

Is there a way?

like image 356
Sree Hari Avatar asked Oct 12 '16 10:10

Sree Hari


People also ask

How do I concatenate all values in a single column?

Use the CONCATENATE function: Use the CONCATENATE function in column D: =CONCATENATE(A1,B1,C1). In the menu bar, select Insert, Function. Click Text functions and select CONCATENATE.

How do I concatenate all values in a column in SQL?

All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How do I concatenate text from multiple rows into a single text string in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.

How do you concatenate in MySQL?

CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.


2 Answers

You could use a combination of CONCAT and GROUP_CONCAT

Query

SELECT GROUP_CONCAT(CONCAT('"', A, '"')) AS `combined_A`
FROM `your_table_name`;

And if you want to remove the duplicates. Then use DISTINCT with GROUP_CONCAT.

Query

SELECT GROUP_CONCAT(DISTINCT CONCAT('"', `A`, '"')) AS `combined_A`
FROM `your_table_name`;

SQL Fiddle demo

like image 91
Ullas Avatar answered Oct 26 '22 00:10

Ullas


Use GROUP_CONCAT() function to achive this.

SELECT GROUP_CONCAT(<Type your column name here> SEPARATOR ', ') FROM <Table Name>;

Query for your provided sample example :

SELECT GROUP_CONCAT(A SEPARATOR ', ')  FROM Table1;
like image 37
Raj K Pachauri Avatar answered Oct 25 '22 22:10

Raj K Pachauri