|
EMP |
ID |
Name |
Country |
Salary |
1 |
Vijay |
India |
6000 |
2 |
Bill |
USA |
8000 |
3 |
Kris |
France |
3000 |
|
---- Example 1
DECLARE @csv VARCHAR(4000)
SELECT @csv = COALESCE(@csv+', ' , '') + Country FROM EMP
SELECT @csv as 'Comma Separated Values'
Output |
Comma Separated Values |
India, USA, France |
---- Example 2
EMP |
Country |
Name |
India |
Vijay |
India |
Gautam |
India |
Raj |
USA |
Bill |
USA |
Steve |
USA |
Kris |
SELECT
t1.Country,
People = substring((SELECT ( ', ' + Name )
FROM EMP t2
WHERE t1.Country = t2.Country
ORDER BY
Country,
Name
FOR XML PATH( '' )
), 3, 1000 )FROM EMP t1
GROUP BY Country
OutPut |
Country |
People |
India |
Gautam, Raj, Vijay |
USA |
Bill, Kris, Steve |
|