Concat all column values in sql

前端 未结 12 630
迷失自我
迷失自我 2020-12-01 00:07

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
         


        
相关标签:
12条回答
  • 2020-12-01 00:41

    SQL Server 2008 R2:

    declare @ColumnNameList VARCHAR(MAX)
    
    
     SELECT @ColumnNameList  = COALESCE(@ColumnNameList +',' ,'') + ColumnName 
                         FROM 
                           <<table name>>
    
    select @ColumnNameList 
    
    0 讨论(0)
  • 2020-12-01 00:51

    Select ([col1] +','+[col2]+','+ [col3]+','+[col4]) as [MyCol] From [Table]

    0 讨论(0)
  • 2020-12-01 00:53

    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
    
    0 讨论(0)
  • 2020-12-01 00:54

    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;
    
    0 讨论(0)
  • 2020-12-01 00:54

    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

    0 讨论(0)
  • 2020-12-01 00:55

    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)
    
    0 讨论(0)
提交回复
热议问题