question

munabhai avatar image
munabhai asked

Merge Data from rows

Create table EmployeeWork ( empid int, CountryWorkAt Varchar(20) ) insert into EmployeeWork values (1,'China') insert into EmployeeWork values (1,'Germany') insert into EmployeeWork values(1,'USA') insert into EmployeeWork values(2,'China') insert into EmployeeWork values(3,'India') insert into EmployeeWork values(3,'USA') insert into EmployeeWork values(4,'China') insert into EmployeeWork values(4,'USA') insert into EmployeeWork values(4,'India') insert into EmployeeWork values(4,'Germany') Merge each row base on empid Output should look like this 1 China, Germmany, USA 2 China 3 India, USA 4 China, USA, India, Germmany
merge
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

JohnM avatar image
JohnM answered
Would this work for you? SELECT DISTINCT empid, CountryWorkAt = REPLACE( ( SELECT CountryWorkAt AS [data()] FROM EmployeeWork ew WHERE ew.empID = e.empID ORDER BY empID FOR XML PATH ('') ), ' ', ',') FROM EmployeeWork e ORDER BY empID Solution modified from http://databases.aspfaq.com/general/how-do-i-concatenate-strings-from-a-column-into-a-single-row.html Hope this helps!
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Pavel Pawlowski avatar image Pavel Pawlowski commented ·
+1 @John Morehouse, I only suggest to modify the query to use **`STUFF`** instead of `REPLACE` because in case you will have a country name sosisting from more than one word, then the words will be separated by comma in final output, as REPLACE will replace all the occurences of space. SELECT empid, CountryWorkAt = STUFF( (SELECT ',' + CountryWorkAt FROM EmployeeWork we WHERE we.empID = e.empID FOR XML PATH ('')), 1, 1, '') FROM EmployeeWork e GROUP BY empid
2 Likes 2 ·
JohnM avatar image JohnM commented ·
+1 @Pavel Pawlowski. Excellent suggestion. I didn't think about countries with a space in the name. Duh!
0 Likes 0 ·
munabhai avatar image
munabhai answered
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

munabhai avatar image
munabhai answered
Thank you all
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.