1

I'm having a bit of trouble implementing the XML PATH method of concatenating multiple rows. So, given the following sql-table, temptable

user | userid | email    |   group

a      usera    [email protected]     admin
a      usera    [email protected]     test
a      usera    [email protected]     edit
b      userb    [email protected]     read
b      userb    [email protected]     write
c      userc    [email protected]     read
c      userc    [email protected]     write

i receive with this code the following:

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]

result:

user |   group

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

but i need this

    user | userid | email    |   group

    a      usera    [email protected]     admin,test,edit
    b      userb    [email protected]     read,write
    c      userc    [email protected]     read,write
1
  • just edited you sql script Commented Oct 29, 2018 at 10:56

2 Answers 2

1

Try below

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
Sign up to request clarification or add additional context in comments.

Comments

0

Just include other column also in group by clause :

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;

However, DISTINCT would also solve your problem :

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.