Howdy
I have a table with a column containing a duplicate values in order_no, and I would like to combine associated values in tracking_no into perhaps a new table, where there will be only ONE row with the order_no, but with tracking_no values comma separated.
SELECT
a.order_no,
STUFF(b.tracking_numbers,1,1,'') AS TrackingNumbers
FROM
(SELECT DISTINCT order_no FROM shipping_data) AS a
CROSS APPLY
(
SELECT ','+tracking_no
FROM shipping_data c
WHERE c.order_no = a.order_no
ORDER BY tracking_no
FOR XML PATH('')
)b(tracking_numbers);
if it wouldn't require much time or effort, I'd press my luck further by asking how I might
add in additional columns that exist in the shipping_data table...
You can add other columns - but if for a given order_no, the other columns have different values in different rows, then do you want to show all such rows? Or do you want to show just one row for a given order_no? If you want to show only one row for a given order_no, how do you pick which value from the other column to show?
Assuming you want to show a row for each unique combination of order_no, OtherCol1 and OtherCol2,
SELECT
a.order_no,
a.otherCol1,
a.otherCol2
STUFF(b.tracking_numbers,1,1,'') AS TrackingNumbers
FROM
(SELECT DISTINCT order_no,otherCol1,otherCol2 FROM shipping_data) AS a
CROSS APPLY
(
SELECT ','+tracking_no
FROM shipping_data c
WHERE c.order_no = a.order_no
ORDER BY tracking_no
FOR XML PATH('')
)b(tracking_numbers);