-2

i have a table in which i want to get column values into single record separated by commaenter image description here

Pranay Kumar
  • 78
  • 10

3 Answers3

4

using the stuff() with select ... for xml path ('') method of string concatenation.

select col1, col2, col3 = stuff(
  (
  select ','+i.col3
    from t as i
    where i.col1 = t.col1
  for xml path (''), type).value('.','nvarchar(max)')
  ,1,1,'')
from t
group by col1, col2

rextester demo: http://rextester.com/QXH88855

returns:

+------+------+-------------+
| col1 | col2 |    col3     |
+------+------+-------------+
|    1 | roy  | a,f,g,h     |
|    2 | sam  | h,k,l       |
|    3 | joe  | q,w,e,r,t,y |
+------+------+-------------+
SqlZim
  • 37,248
  • 6
  • 41
  • 59
2

If SQL Server 2017 or Vnext or SQL Azure you can use string_agg

SELECT col1, col2, STRING_AGG(col3, ',') from yourtable
   GROUP BY col1, col2
Kannan Kandasamy
  • 13,405
  • 3
  • 25
  • 38
0

Formatting the output really should be done in the program that receives the data. You can export from SQL Server Management studio to csv by selecting "output to file" on the toolbar and configuring comma delimited output.

If you really need to combine the columns into a comma separated single value:

SELECT CAST(col1 AS NVARCHAR(100)) + N',' + CAST(col2 AS NVARCHAR(100)) + N',' + CAST(col3 AS NVARCHAR(100)) FROM table

Chris Smith
  • 5,326
  • 29
  • 29