【问题标题】:SQL Combine multiple rows into one column and get name from IdsSQL将多行合并为一列并从ID中获取名称
【发布时间】:2018-06-04 11:23:11
【问题描述】:

考虑一个数据库表 connectouser 包含两个 ID:

 connectouser
compID    coopID
   1         1
   1         2
   1         3
   2         1
   2         2

考虑另一个数据库表 coop 持有两个 ID:

coop
ID   Name
1     ABC
2     DEF
3     GHJ

我想要以下输出:

Result
compID   coopname
1        ABC,DEF,GHJ
2        ABC,DEF

谁能帮帮我。

【问题讨论】:

标签: sql sql-server string-concatenation


【解决方案1】:

该问题被标记为 MySQL 以获得此答案。

这是和group_concat()的群组:

select cu.compId, group_concat(co.name order by co.id) as coopnames
from connectouser cu join
     coop co
     on cu.coopID = co.ID
group by cu.compId;

在 SQL Server 中,您可以:

select cu.compId,
       stuff( (select ',' + co.name
               from coop co
               where cu.coopID = co.ID
               order by co.id
               for xml path ('')
              ), 1, 1, ''
            ) as names
from connectouser cu;

最新版本的 SQL Server 支持string_agg(),这是一种更好的方法。

【讨论】:

  • 显示错误group_contact() is not Recognized built in function in sql
  • 只需复制并粘贴 SQL @HatimRanapurwala .. 该函数称为 group_concat() 而不是 group_contact()
  • 抱歉输入错误它显示错误group_concat() is not Recognized built in function in sql
  • 或者您使用的是非常旧的 MySQL 版本或根本没有 MySQL,我认为这更有可能是@HatimRanapurwala ...因为“在 sql 中无法识别内置函数”在我看来就像 SQL服务器错误消息。
猜你喜欢
  • 2020-06-09
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
相关资源
最近更新 更多