Concat all column values in sql

前端 未结 12 683
迷失自我
迷失自我 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:57

    Here is the answer you are looking for; I had a feeling the solution lay in the CONNECT BY operation, I just hadn't used the SYS_CONNECT_BY_PATH pseudocolumn before (which displays the full path to the node in a tree, separating node names by a "/"). Assuming that your set of "foo" values before are multiple rows in a table, grouped by a column "myKey", e.g.:

    myKey    foo
    -------- ----------
    group 1  apple
    group 1  orange
    group 1  pear
    group 2  ape
    group 2  bear
    group 2  kitten
    

    you can treat the data as if it were a tree schema, and pretend that the values of each group represent nodes going down a branch. In that case, you'd do this:

      SELECT myKey
           , SUBSTR(MAX(REPLACE(SYS_CONNECT_BY_PATH(foo, '/')
                               ,'/'
                               ,' '
                               )
                       )
                   ,2
                   ) FooConcat
        FROM ( SELECT MyKey
                    , Foo
                    , row_number() OVER (Partition by myKey order by myKey) NodeDepth
                 FROM MyTable
             )
       START WITH NodeDepth = 1
     CONNECT BY PRIOR myKey = myKey
         AND PRIOR NodeDepth = NodeDepth -1
    GROUP BY myKey
    ;
    

    Of course, the order of the concatenated values would be random; if your table had another column ("bar") that you could use as an ordering field that was ascending and contiguous, you could dispense with the subquery (which only exists to put an imaginary depth to the tree) and use the table directly, replacing NodeDepth with bar.

提交回复
热议问题