1

I am trying to merge rows of employee DB table

Here is my original table

enter image description here

I want to merge rows based on department. here is my expected result.

enter image description here

I tried using FOR XML PATH('')), 1, 1, '') but I canroll up only one column.

I know we have similar question here but its rolling up only one column.

any help is much appreciated

Community
  • 1
  • 1
saTech
  • 421
  • 4
  • 7
  • 19

3 Answers3

4

Just use the same method for the other columns:

SELECT
    t.Department,
    Worker = 
        STUFF((
            SELECT ';' + Worker
            FROM tbl 
            WHERE Department = t.Department
            ORDER BY Worker
            FOR XML PATH(''), TYPE
        ).value('text()[1]','NVARCHAR(MAX)'), 1, 1, N''),
    Phone = 
        STUFF((
            SELECT ';' + Phone
            FROM tbl 
            WHERE Department = t.Department
            ORDER BY Worker
            FOR XML PATH(''), TYPE
        ).value('text()[1]','NVARCHAR(MAX)'), 1, 1, N''),
    Ext = 
        STUFF((
            SELECT ';' + Ext
            FROM tbl 
            WHERE Department = t.Department
            ORDER BY Worker
            FOR XML PATH(''), TYPE
        ).value('text()[1]','NVARCHAR(MAX)'), 1, 1, N'')
FROM tbl t
GROUP BY t.Department
Felix Pamittan
  • 31,544
  • 7
  • 41
  • 67
0

You can also try the query below:

SELECT
    t.Department,
    Worker = STUFF((
                SELECT ';' + s.Worker
                FROM
                    YourTable s
                WHERE
                    s.Department = t.Department
                FOR XML PATH('')),1,1,''),
    Phone = STUFF((
                SELECT ';' + CAST(s.Phone AS VARCHAR(25))
                FROM
                    YourTable s
                WHERE
                    s.Department = t.Department
                FOR XML PATH('')),1,1,''),
    Ext = STUFF((
                SELECT ';' + CAST(s.Ext AS VARCHAR(25))
                FROM
                    YourTable s
                WHERE
                    s.Department = t.Department
                FOR XML PATH('')),1,1,'')
FROM YourTable t
GROUP BY t.Department
dee.ronin
  • 1,040
  • 12
  • 22
0

I just found this online a couple days ago. I tried it and it worked great for me. Give it a go and see how you get along.

http://groupconcat.codeplex.com/

http://groupconcat.codeplex.com/releases/view/618110

Create TABLE testtable( Customer VARCHAR(50), Product VARCHAR(50), Method VARCHAR(50), INDEX ix CLUSTERED (Customer) )

INSERT INTO testtable (Customer, Product, Method) VALUES ('John', 'Computer', 'Credit'), ('John', 'Mouse', 'Cash'), ('Will', 'Computer', 'Credit'), ('Will', 'Mouse', 'Cash'), ('Will', 'Speaker', 'Cash'), ('Todd', 'Computer', 'Credit')

Select * From testtable

SELECT Customer,dbo.GROUP_CONCAT(product),dbo.GROUP_CONCAT(method) FROM testtable GROUP BY Customer

enter image description here

ASH
  • 20,759
  • 19
  • 87
  • 200