Search code examples
sql-server-2008coalescecsv

Return columns as comma separated, for more than one condition on key or more than one row


I have a table with values:

Key1     Key2     ColumnKey 
1        idx      here
1        idx      there

2        idx      where
2        idx      why

I need to return, for both Key1, Key2 being same, columnKey separated by commas.

Example: Instead of

1   idx      here
1   idx      there 

Need to return

1      idx        here, there

Query that works:

  DECLARE @commaSeperatedRes NVARCHAR(MAX);    
    SELECT @commaSeperatedRes =  COALESCE(@commaSeperatedRes + ', ', '') + ColumnKey 
      FROM Table1  
     WHERE Table1.Key1= 1 AND Table1.Key2 = 'idx';        
    print @commaSeperatedRes

Problem is, I need to return this for more than one row:

   1 idx     here, there
   2  idx    where, why 


  DECLARE @commaSeperated NVARCHAR(MAX);    
    SELECT @commaSeperatedRes =  COALESCE(@commaSeperated + ', ', '') + ColumnKey 
      FROM Table1  
     WHERE (Table1.Key1= 1  and Table1.Key2 = 'idx') 
         OR
         ( Table1.Key1 = 2 Table1.Key2 = 'idx')

 print @commaSeperatedRes

Also, I will insert these results into a temporary table so the values are clubbed with some more columns from other tables. Ideally, my temporary table that I'll work with should look like this:

  TKey1     TKey2     TColumnKey 
    1        idx      here, there    
    2        idx      where, why

Solution

  • SELECT t1.Key1, t1.Key2, 
           STUFF((SELECT ', ' + ColumnKey
                      FROM Table1 t2
                      WHERE t2.Key1 = t1.Key1
                          AND t2.Key2 = t1.Key2
                      ORDER BY ColumnKey
                      FOR XML PATH('') ),1,2,'') AS TColumnKey
        FROM Table1 t1
        GROUP BY t1.Key1, t1.Key2;