7

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?

3 Answers 3

15

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

2
  • What if I need a1&a2&a3&a4&a5 (no , in between)?
    – June
    Apr 30, 2021 at 17:57
  • 1
    @June : You can use separator '&' with Group_Concat
    – Ullas
    May 2, 2021 at 6:54
3

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;
0

You will have to use a group concat function to accomplish something similar

SELECT , GROUP_CONCAT(A SEPARATOR ', ') FROM Table1 GROUP BY

In the event you don't have an id you will have to use a constant for the grouping. Also note that the result you have has a 1024 byte character limit unless you override it

1
  • No GROUP BY in this instance
    – Strawberry
    Oct 12, 2016 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.