I'm trying to concatenate multiple rows of a query into a string, but not getting the results I was expecting. The example that I'm working with should be returning one row, with the values of row 1 and row 2 concatenated in row 1 separated by commas. Instead, I'm getting two rows, with row 1 concatenated to itself and row 2 unchanged except for a comma in front.
Expected Result:
TYPEA, TYPE B
Actual Result:
,TYPEA,TYPEA ,TYPEB
SELECT DISTINCT t.ID,
t.TicketNumber,
tc.Description AS Code,
(SELECT ',' + order_type
FROM Table_Order_Account oa
WHERE oa.service_account = cs.CustomerServiceNumber
FOR XML PATH ('')) AS Code3,
oa.order_type AS Code2
FROM Table_Ticket t
WHERE (T.TicketType = 2 OR (t.tickettype = 1 AND tpc.Description = 'Records Update Needed'))
What am I doing wrong here? Thanks!
Note: I'm working in SQL Server 2014, so STRING_AGG isn't an option for me.
The reason you are getting extra rows is probably related to the outer query missing a
GROUP BY. It only usesDISTINCT, but it includesoa.order_type AS Code2, so it's not going to reduce the rows further.Instead, remove that column and the
LEFT JOIN Table_Order_Account as oacompletely, and use something likeGROUP BY t.ID, t.TicketNumber, tc.Description.You also need to knock off the leading comma. You can use the
STUFFfunction to do that.The third parameter of
STUFFshould be the length of the separator.You should also use
.valueto unescape any possible XML characters.And don't use
NOLOCK, it has serious data integrity implications.