sql server使用FOR XML PATH连接多行

时间:2018-10-29 10:09:15

标签: sql sql-server

我在实现连接多行的XML PATH方法时遇到了一些麻烦。因此,给定以下sql-table,temptable

user | userid | email    |   group

a      usera    a@a.com     admin
a      usera    a@a.com     test
a      usera    a@a.com     edit
b      userb    b@a.com     read
b      userb    b@a.com     write
c      userc    c@c.com     read
c      userc    c@c.com     write

我收到以下代码:

SELECT a.[user],

STUFF((SELECT  ', ' +  [group] [text()]
      FROM [temptable] 
      WHERE [user] = a.[user]
      for XML PATH (''),TYPE).
      value('.','NVARCHAR(MAX)'),1,2,'') AS [group]

FROM [temptable] as a
GROUP BY a.[user]

结果:

user |   group

a      admin,test,edit
b      read,write
c      read,write

但是我需要这个

    user | userid | email    |   group

    a      usera    a@a.com     admin,test,edit
    b      userb    b@a.com     read,write
    c      userc    c@c.com     read,write

2 个答案:

答案 0 :(得分:0)

group by子句中也包括其他列:

SELECT a.[user], userid, email,
       STUFF((SELECT  ', ' +  [group] [text()]
              FROM [temptable] 
              WHERE [user] = a.[user]
              FOR XML PATH (''),TYPE).value('.','NVARCHAR(MAX)'),1,2,''
            ) AS [group]
FROM [temptable] AS a
GROUP BY a.[user], userid, email;

但是,DISTINCT也可以解决您的问题:

SELECT DISTINCT a.[user], userid, email,
           STUFF((SELECT  ', ' +  [group] [text()]
                  FROM [temptable] 
                  WHERE [user] = a.[user]
                  FOR XML PATH (''),TYPE).value('.','NVARCHAR(MAX)'),1,2,''
                ) AS [group]
FROM [temptable] AS a;

答案 1 :(得分:0)

尝试以下

SELECT a.[user],a.userid,a.email
STUFF((SELECT  ', ' +  [group] [text()]
      FROM [temptable] b on a.[user]=b.[user]
      for XML PATH (''),TYPE).
      value('.','NVARCHAR(MAX)'),1,2,'') AS [group]
FROM [temptable] as a
GROUP BY a.[user],a.userid,a.email