我在实现连接多行的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
答案 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