1

I have a table with two columns like this

col1     col2
 a        b
 b        a
 c        d
 d        a

I want to get distinct values of these two columns combined with comma separated. Expected out put is like this

a,b,c,d
None
  • 5,582
  • 21
  • 85
  • 170
  • possible duplicate of [SQL group\_concat function in SQL Server](http://stackoverflow.com/questions/8868604/sql-group-concat-function-in-sql-server) –  Nov 05 '13 at 12:44

2 Answers2

4

The following example concatenate row values into a variable

DECLARE @val nvarchar(max)
SELECT @val = COALESCE(@val + ',' + col1, col1)
FROM (SELECT col1
      FROM dbo.twoColumns
      UNION
      SELECT col2
      FROM dbo.twoColumns
      ) x
SELECT @val

Demo on SQLFiddle

Aleksandr Fedorenko
  • 16,594
  • 6
  • 37
  • 44
2

try this , its very much easy i think

select group_concat(distinct(c)) as d
from 
(
  select col1 c from your_table
  union
  select col2 c from your_table
) as d
uvais
  • 416
  • 2
  • 6