2

I am using MSSQL database and I have a table named UserDepartments that has all the Departments ID that assigned to one user as the following

UserID | DepartmentID
1      | 220
1      | 330
1      | 210
1      | 100
2      | 330
2      | 440
3      | 550

what i want exactly to create a VIEW of that table that show it as the following

UserID | Departments
1      | 220, 330, 210, 100
2      | 330, 440
3      | 550

is it possible to do it using MSSQL?

Cœur
  • 37,241
  • 25
  • 195
  • 267
msytNadeem
  • 173
  • 1
  • 4
  • 15
  • 1
    possible duplicate [Output a comma-separated list in a column in SQL Server](http://stackoverflow.com/a/13053078/1699210) – bummi Jul 16 '13 at 05:20
  • thanks man can you post it as an answer so i can mark it as an answer? – msytNadeem Jul 16 '13 at 05:24
  • 1
    there is no new answer needed, this was anwered many times. You may vote on existing answers. Have fun. – bummi Jul 16 '13 at 05:35

1 Answers1

2

Try this one -

Query:

DECLARE @temp TABLE
(
       UserID INT
     , DepartmentID INT
)

INSERT INTO @temp (UserID, DepartmentID)
VALUES 
     (1, 220),(1, 330),
     (1, 210),(1, 100),
     (2, 330),(2, 440),
     (3, 550)

SELECT 
       t.UserID
     , DepartmentID = STUFF((
          SELECT ', ' + CAST(DepartmentID AS VARCHAR(10))
          FROM @temp t2
          WHERE t2.UserID = t.UserID
          FOR XML PATH(''), TYPE).value('.', 'VARCHAR(1024)'), 1, 2, '')                            
FROM ( 
     SELECT DISTINCT UserID 
     FROM @temp
) t

Output:

UserID      DepartmentID
----------- -----------------------------
1           220, 330, 210, 100
2           330, 440
3           550
Devart
  • 119,203
  • 23
  • 166
  • 186