Total Pageviews

2018/11/09

[SQL Server] Utilize FOR XML PATH to merge multiple rows into one row

Problem
Assume I get two rows from the following SQL statement:
select t1.CASEID, t1.PID, t1.NAME, t2.QVALUE + CHAR(10) + t2.AVALUE as QA
from TEXT_MAIN t1, TEXT_QA t2
where t1.CASEID = 'W00000003944' and t1.RID = t2.RID



If I would like to merge the two rows into one row:


How-To
You can use FOR XML PATH to fulfill this requirement, here has the example
select t1.CASEID, t1.PID, t1.NAME,
    (select t2.QVALUE + CHAR(10) + t2.AVALUE + CHAR(10)
     from TEXT_QA t2
     where t1.RID = t2.RID
     FOR XML PATH('')) as QA
from TEXT_MAIN t1
where t1.CASEID = 'W00000003944' 


No comments: