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
SQL Server 2008 R2:
declare @ColumnNameList VARCHAR(MAX)
SELECT @ColumnNameList = COALESCE(@ColumnNameList +',' ,'') + ColumnName
FROM
<<table name>>
select @ColumnNameList
Select ([col1] +','+[col2]+','+ [col3]+','+[col4]) as [MyCol] From [Table]
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
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;
I found the answer on How to concatenate all the records in a column returned by a query into one varchar string in T-SQL?
declare @s varchar(8000)
select @s = coalesce(@s + col, col) from tbl
This should solve
Assuming that it's one column with multiple values, this approach works for MS SQL Server (I can't speak for other systems).
declare @result varchar(max)
set @result = ''
select @result = @result + RES
from (query goes here)