Search code examples
sqlsql-serverfor-xml-path

SQL SERVER Combine multiple rows with multiple columns into single row with single column


Ok guys this has got me rolling my eyes for a few days now. Let's say i have two tables (or more) like below.

TABLE1

ID  | NAME      | DATE          | MORE COLS....
1   | MARK      | 2018-31-10    | ....
2   | JOHN      | 2018-29-10    | ....
...

TABLE2

FK_TBL1_ID | Data1     | Data2     | 
1          | 11111     | 33333     | 
1          | 22222     | 44444     | 
2          | 12345     | 67899     | 
...

And i would like to combine multiple columns of each row with same id of these tables into A SINGLE ROW and a SINGLE COLUMN like below. Each new "row" will be divided from the previous with ';'.

QUERY RESULT

ID  | NAME      | DATE          |       Data1Data2        | 
1   | MARK      | 2018-31-10    |  1111 3333; 2222 4444;  | 
2   | JOHN      | 2018-29-10    |  12345 67899            | 

How would you go about doing that? i found examples on FOR XML PATH but only when there are multiple rows with two columns and combined on different rows.


Solution

  • Here is an example with your data:

    select t1.*,
           stuff( (select '; ' + coalesce(data1, '') + ' ' + coalesce(data2, '')
                   from table2 t2
                   where t2.FK_TBL1_ID = t1.id
                   for xml path ('')
                  ), 1, 2, ''
                ) as Data1Data2
    from table1 t1;