如何在sql中连接多个具有相同id的行? [英] How to concatenate many rows with same id in sql?

查看:39
本文介绍了如何在sql中连接多个具有相同id的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表格包含两个字段的详细信息:

My table contains the details like with two fields:

ID      DisplayName
1        Editor
1        Reviewer
7        EIC
7        Editor
7        Reviewer
7        Editor
19       EIC
19       Editor
19       Reviewer

我想通过 DisplayName 获取独特的详细信息,例如

I want get the unique details with DisplayName like

1 位编辑、审稿人 7 位 EIC、编辑、审稿人

不要获取 ID 为 7 的重复值

Don't get duplicate value with ID 7

如何合并显示名称详细信息?如何编写查询?

How to combine DisplayName Details? How to write the Query?

推荐答案

SQL-Server 中,您可以通过以下方式进行:

In SQL-Server you can do it in the following:

查询

SELECT id, displayname = 
    STUFF((SELECT DISTINCT ', ' + displayname
           FROM #t b 
           WHERE b.id = a.id 
          FOR XML PATH('')), 1, 2, '')
FROM #t a
GROUP BY id

测试数据

create table #t 
(
id int,
displayname nvarchar(max)
)

insert into #t values    
 (1 ,'Editor')
,(1 ,'Reviewer')
,(7 ,'EIC')
,(7 ,'Editor')
,(7 ,'Reviewer')
,(7 ,'Editor')
,(19,'EIC')
,(19,'Editor')
,(19,'Reviewer')

输出

id  displayname
1   Editor, Reviewer
7   Editor, EIC, Reviewer
19  Editor, EIC, Reviewer

这篇关于如何在sql中连接多个具有相同id的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆