CONCAT列SQL

时间:2018-07-16 08:50:19

标签: sql oracle string-aggregation

我需要您的帮助来解决以下问题

     column1    Column2 
          1       a
          1       b
          2       c
          3       d
          4       e

我想与col2的元素联系以获得相同的col1值,并将结果作为变量返回到单列中。

结果:| 1 | a,b |

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

使用concat函数

 select concat(case when t.column1 is not null then t.column1 else end,
 case when t.column2 is not null then t.column2 else end) as col1 from   your_table as t
inner join
(
select column1 from your_table
group by column1
having count(*)>1
) as T1
t.column1=T1.column1

答案 1 :(得分:0)

根据需要填充tbename和column1,column2

      SELECT  distinct     CAT.column1 AS [column1],
               STUFF((    SELECT ',' + SUB.column2 AS [text()]

                     FROM tbename SUB
                     WHERE
                     SUB.column1 = CAT.column1
                     FOR XML PATH('')
                       ), 1, 1, '' )

        AS [column2]
  FROM  tbename  CAT

对于oracle,代码11g +

select column1, listagg(column2,',') within group( order by column1 ) 
  from tbename group by gr