tblA has columns EOD_Job_ID and Firm_ID
tblA
EOD_Job_ID Firm_ID
1 111
1 222
2 333
2 444
How to group by EOD_Job_ID and combine the Firm_IDs?
Desired result:
EOD_Job_ID Firm_ID
1 111,222
2 333,444
I'd suggest to use the FOR XML PATH method to concatenate strings. Just make sure in case your Firm_ID is of integer type you cast it to (n)nvarchar first
SELECT DISTINCT EOD_Job_ID, STUFF((SELECT ',' + CAST(Firm_ID AS nvarchar(3))
FROM @tblA
WHERE EOD_Job_ID = tbl.EOD_Job_ID FOR XML PATH('')),1,1,'') AS Firm_ID
FROM @tblA tbl
If you adjust the code from that link to you table, it will be:
SELECT Main.EOD_Job_ID,
LEFT(Main.Students,Len(Main.Students)-1) As Students
FROM
(
SELECT DISTINCT ST2.EOD_Job_ID,
(
SELECT cast(ST1.Firm_ID as varchar(5)) + ',' AS [text()]
FROM tblA ST1
WHERE ST1.EOD_Job_ID = ST2.EOD_Job_ID
ORDER BY ST1.EOD_Job_ID
FOR XML PATH ('')
) [Students]
FROM tblA ST2
) [Main]
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.