简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM