How do I concatenate SQL queries into a string?

How can I get individual values ​​from a column and concatenate them into one row? Thank.

For example, I have a column like

fruit_name
------
apple
apple
apple
banana
orange
orange
.
.
.

      

I want to create the result as apple, banana, orange...

Here is the query I tried, but it will give the result apple, apple, apple, banana...

SELECT LISTAGG(fruit_name,', ') WITHIN GROUP (ORDER BY fruit_name) "fruit_List" FROM FRUIT_TABLE;

      

I do not know how to make the result perfect.

+3


source to share


4 answers


You can use MySQL function GROUP_CONCAT()

to solve your problem:

SELECT GROUP_CONCAT(t.fn)
FROM
(
    SELECT fruit_name fn
    FROM FRUIT_TABLE
    GROUP BY fruit_name
) t

      

The default delimiter in GROUP_CONCAT

is the comma that you specified in your original problem.



Update:

I do justice to this solution by @ cars10 who pointed out that everyone initially got it wrong.

+1


source


Try this query,



SELECT GROUP_CONCAT(DISTINCT fruit_name) FROM FRUIT_TABLE ORDER BY fruit_name;

      

+1


source


You can use the following query using GROUP_CONCAT

as LISTAGG

not available in mysql:

SELECT GROUP_CONCAT(DISTINCT fruit_name ORDER BY fruit_name ASC SEPARATOR ',') as fruit_List
FROM FRUIT_TABLE

      

GROUP_CONCAT

has DISTINCT

and ORDER BY

attributes included

+1


source


edit: (my first version was clearly wrong!)

select group_concat(fn) fruit_list
from (select fruit_name fn 
         from fruit_table 
         group by fruit_name) fruits

      

It works now, see here http://sqlfiddle.com/#!9/bfbf4/2 , but Nikhil Batra's solution is by far the best choice!

0


source







All Articles