如何在sql中连接多个具有相同id的行?

时间:2016-02-03 09:23:19

标签: sql sql-server

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

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

我希望获得DisplayName的独特细节,如

1 Editor,Reviewer 7 EIC,Editor,Reviewer

不要使用ID 7

获取重复值

如何组合DisplayName详细信息?如何编写查询?

7 个答案:

答案 0 :(得分:23)

SQL-Server 中,您可以执行以下操作:

<强> QUERY

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

答案 1 :(得分:7)

DECLARE @t TABLE
(
    ID INT,
    DisplayName VARCHAR(50)
)
INSERT INTO @t (ID, DisplayName)
VALUES
    (1 , 'Editor'),
    (1 , 'Reviewer'),
    (7 , 'EIC'),
    (7 , 'Editor'),
    (7 , 'Reviewer'),
    (7 , 'Editor'),
    (19, 'EIC'),
    (19, 'Editor'),
    (19, 'Reviewer')

SELECT *, STUFF((
            SELECT DISTINCT ', ' + DisplayName
            FROM @t
            WHERE ID = t.ID
            FOR XML PATH('')), 1, 2, '')
FROM (
    SELECT DISTINCT ID
    FROM @t
) t

输出 -

----------- ------------------------
1           Editor, Reviewer
7           Editor, EIC, Reviewer
19          Editor, EIC, Reviewer

关于字符串聚合的帖子:

http://www.codeproject.com/Articles/691102/String-Aggregation-in-the-World-of-SQL-Server

答案 2 :(得分:3)

对于MySQL:
SELECT id, GROUP_CONCAT(displayname) FROM tableName GROUP BY id

参考:http://www.sqlines.com/mysql/functions/group_concat

答案 3 :(得分:2)

SQL Server 2017+ 和 SQL Azure:STRING_AGG

从下一版本的 SQL Server 开始,我们最终可以跨行串联,而无需求助于任何变量或 XML 巫术。

STRING_AGG (Transact-SQL)

SELECT ID, STRING_AGG(DisplayName, ', ') AS DisplayNames
FROM TableName
GROUP BY ID

答案 4 :(得分:1)

以及oracle数据库

g

答案 5 :(得分:0)

谢谢大家,

SELECT Distinct
    t1.ID,
    MAX(STUFF(t2.x_id,1,1,'')) AS DisplayName
FROM Table t1
CROSS apply(
    SELECT Distinct ', ' + SUBSTRING(t2.DisplayName,1,2)
    FROM Table t2
    WHERE t2.ID = t1.ID AND t2.DisplayName > ''
    FOR xml PATH('')
) AS t2 (x_id)
GROUP BY
    t1.ID
order by 1
GO

答案 6 :(得分:0)

更改分隔符的使用

SELECT id, GROUP_CONCAT(displayname SEPARATOR ';') FROM tableName GROUP BY id

这会将分隔符从逗号更改为分号:)