1

I have a table with these sample records:

CREATE TABLE USERROLES(User ID int,ApplicationID int,Roleid INT) 

INSERT INTO USERROLES
VALUES (11, 1, 1), (11, 1, 5), (11, 3, 5);

I want to display below output.

USERID  ApplicationID   Roles
-----------------------------
11         1             1,5
11         3              5

ApplicationID=1 is duplicates for ROLES 1,5.So it should display in single row. I am using SQL Server 2016

D-Shih
  • 44,943
  • 6
  • 31
  • 51
Ram
  • 727
  • 2
  • 16
  • 33
  • You may read this: https://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-microsoft-sql-server-2005. – Zhorov Oct 27 '18 at 06:43

3 Answers3

2

You can try to use STUFF with FOR XML let Roleid combine.

 SELECT 
  UserID,
  ApplicationID,
  STUFF((
    SELECT ',' + cast(Roleid as varchar(max))
    FROM USERROLES tt
    WHERE ApplicationID = t1.ApplicationID
    FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
  ,1,1,'') AS Roles
FROM USERROLES t1
group by 
  UserID,
  ApplicationID

sqlfiddle

Result

serID   ApplicationID   Roles
11       1              1,5
11       3              5
D-Shih
  • 44,943
  • 6
  • 31
  • 51
2

You can try the below query

    SELECT DISTINCT UserID, ApplicationID, Roles = 
    STUFF((SELECT ', ' + CAST(Roleid as Varchar)
           FROM userroles b 
           WHERE b.UserID = a.UserID and a.ApplicationID = b.ApplicationID 
          FOR XML PATH('')), 1, 2, '')
FROM userroles a
GROUP BY UserID, ApplicationID, Roleid

Hope this will help you.

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
1
Sometime adding other string with comma add extra space between both, so use
FOR XML PATH('')), 1, 1, '')

instead of

 FOR XML PATH('')), 1, 2, '')

as shown below and remove space after comma like ','

SELECT DISTINCT UserID, ApplicationID, Roles = 
    STUFF((SELECT ',' + CAST(Roleid as Varchar)
           FROM userroles b 
           WHERE b.UserID = a.UserID and a.ApplicationID = b.ApplicationID 
          FOR XML PATH('')), 1, 1, '')
FROM userroles a
GROUP BY UserID, ApplicationID, Roleid
Saket Yadav
  • 967
  • 1
  • 10
  • 23