Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat all column values in sql

How to concat all column values from differenct rows returned from a sql query into one value? This is an example:

a query returns:

 FOO ------ RES1  RES2  RES3 

now I want to have a result like the following one:

 FOOCONCAT ----- RES1RES2RES3 

Are there any ways to do this in sql?

like image 882
paweloque Avatar asked Jun 09 '09 14:06

paweloque


People also ask

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

Concatenate Rows Using COALESCE 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. In this method, you don't need to worry about the trailing comma.

How do I concatenate multiple columns in SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.

How do I concatenate all values in a single column?

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

How do I concatenate a string in a column in SQL?

To append a string to another and return one result, use the || operator. This adds two strings from the left and right together and returns one result. If you use the name of the column, don't enclose it in quotes. However, in using a string value as a space or text, enclose it in quotes.


2 Answers

In SQL Server:

SELECT  col1 AS [text()] FROM    foo FOR XML PATH ('') 

In MySQL:

SELECT  GROUP_CONCAT(col1 SEPARATOR '') FROM    foo 

In PostgreSQL:

SELECT  array_to_string         (         ARRAY         (         SELECT  col1         FROM    foo         ), ''         ) 

In Oracle:

SELECT  * FROM    (         SELECT  col1, ROW_NUMBER() OVER(ORDER BY 1) AS rn         FROM    foo         MODEL         DIMENSION BY                 (rn)         MEASURES                 (col1, col1 AS group_concat, 0 AS mark)         RULES UPDATE (                 group_concat[rn > 1] =  group_concat[CV() - 1] || col1[CV()],                 mark[ANY] = PRESENTV(mark[CV() + 1], 0, 1)                 )         ) WHERE   mark = 1 
like image 130
Quassnoi Avatar answered Sep 30 '22 08:09

Quassnoi


Quassnoi's Oracle solution is quite impressive, but I found simpler ones using SYS_CONNECT_BY_PATH() rather than the MODEL magic.

SELECT REPLACE(MAX(SYS_CONNECT_BY_PATH(foo, '/')), '/', '') conc FROM (     SELECT T_FOO.*, ROW_NUMBER() OVER (ORDER BY FOO) R FROM T_FOO ) START WITH r=1 CONNECT BY PRIOR r = r-1; 
like image 32
devio Avatar answered Sep 30 '22 09:09

devio