【问题标题】:CONCAT Column SQL [duplicate]CONCAT 列 SQL [重复]
【发布时间】:2018-07-16 08:50:19
【问题描述】:

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

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

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

结果:|1|a,b|

感谢您的帮助。

【问题讨论】:

  • 你是什么 dbms?
  • 你在用什么rdbms
  • 我使用 SQL for Oracle

标签: sql oracle string-aggregation


【解决方案1】:

使用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

【讨论】:

  • SQL Oracle 是不是也一样,因为我用的是那个?
【解决方案2】:

根据需要填写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

适用于代码 11g+ 以下的 oracle

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

【讨论】:

  • SQL Oracle 是不是也一样,因为我用的是那个?
  • 此代码用于 SQL Server 添加 oracle 代码,它将适用于 11g +
猜你喜欢
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
相关资源
最近更新 更多