I am trying to merge rows of employee DB table
Here is my original table
I want to merge rows based on department. here is my expected result.
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
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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.