Given a one to many where an Item can be in many Warehouses, doing a straight join returns duplicate items. I'd like to collapse the data from the warehouse table into strings so that there is one record per item. This works, but is there a more efficient approach that avoids doing 2 separate subselects/subqueries?
SELECT
im.ItemID,
(SELECT WareHouseID + ','
FROM stockStatusSummary WHERE ItemKey = im.ItemKey for xml path (''))
as 'WarehouseIDs',
(SELECT Convert(varchar(20), Round(QtyAvailable,3)) + ','
FROM stockStatusSummary
WHERE ItemKey = im.ItemKey for xml path (''))
as 'WarehouseQuantity'
FROM item im
With the output looking like this:
ItemID WarehouseIDs WarehouseQuantity
------- ------------- -----------------
1 10,20,30, 5,7,9,
2 20,30,40, 6,8,10,
3 30,40,50, 7,9,11,