How can I get distinct values in COALESCE()

Viewed 30681

I have table values in this format

sam
jack
sam
john

Declare @name varchar(max)
select @name = COALESCE(@name + ', ','')+ user_email 
from   PostedCommentMaster where article_id = @id

How can I get distinct value

sam,jack,john

like this.

6 Answers

Best You can use this one.

Declare @name varchar(max)
select @name = COALESCE(@name + ', ','')+ user_email  from (select distinct user_email 
from   PostedCommentMaster where article_id = @id ) as tblTemp

SELECT distinct @name = COALESCE(@name + ', ','')+ user_email from PostedCommentMaster where article_id = @id

I was stuck on same issue. So my solution to this is-

  1. Create a #temp table.
  2. Insert distinct values to your #temp table.
  3. Add your coalesce query.

    create table #emailList (user_email varchar(200))
    insert into #emailList select distinct user_email from   PostedCommentMaster 
    where article_id = @id
    
    Declare @name varchar(max)
    select @name = COALESCE(@name + ', ','')+ user_email 
    from   #emailList
    

    This is also helpful in fetching data from multiple tables using joins.

Related