Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi All,I've got a table named Person which contains a Person_id (PK), Name and Gender.I want to concat all names to one line grouped by gender, for example:Gender NameMale John, AdamFemale Ann, JosephineI tried with the FOR XML function but it won't work. Can somebody help me?Tnx.
James K
Master Smack Fu Yak Hacker
3873 Posts
Posted - 2014-01-17 : 11:18:16
What did you try? Use something like shown below:
CREATE TABLE #tmp(gender CHAR(1), NAME VARCHAR(32));INSERT INTO #tmp VALUES ('M','Joe'),('F','Jane'),('F','Mary'),('F','Liz'),('M','Tom');SELECT gender, STUFF(NAMES,1,1,'') AS NAMESFROM (SELECT DISTINCT gender FROM #tmp) a CROSS APPLY ( SELECT ',' + name FROM #tmp b WHERE b.gender = a.gender FOR XML PATH('')) b(NAMES);DROP TABLE #tmp;