None
None

Reputation: 5670

select distinct elements from two columns with comma separated in sql

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

Upvotes: 1

Views: 1990

Answers (2)

uvais
uvais

Reputation: 416

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

Upvotes: 2

Oleksandr Fedorenko
Oleksandr Fedorenko

Reputation: 16894

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

Upvotes: 4

Related Questions