I'm currently working on a SQL query in T-SQL on SQL Server 2012 with the objective to concate or merge several tables into 1 table and concate several rows. So far it's working out fine. I use STUFF and FOR XML PATH to concate several rows into 1.
Unfortunately, when I want to merge my 2 temporary tables into 1 final result table, the concatinated (merged) rows disappear again.
My tables look the following way:
table #BasicOffers
OfferId | Tile | Manager | DeliveryVersionId |
----------+--------+----------+-------------------|
4 | Offer1 | John Doe | 1 |
5 | Offer2 | Jane Doe | 2 |
table #TmpLabels
DeliveryVersionId | Label |
------------------+-------------------------+
1 | Service, Time, Material |
2 | Consulting, Time |
final result, unfortunately not the desired output. the temporary tables seem to be split-up again:
OfferId | Title | Manager | Delivery
----------+--------+----------+------------------------
4 | Offer1 | John Doe | Service
4 | Offer1 | John Doe | Time
4 | Offer1 | John Doe | Material
5 | Offer2 | Jane Doe | Consulting
5 | Offer2 | Jane Doe | Time
Desired Output:
OfferId | Title | Manager | Delivery
----------+--------+----------+------------------------
4 | Offer1 | John Doe | Service, Time, Material
5 | Offer2 | Jane Doe | Consulting, Time
My query to merge the tables looks like this:
-- Delivery Methods
SELECT [D].DeliveryVersionId, [DM].Label
INTO #TmpLabels
FROM [MySchema].[Delivery] [D]
INNER JOIN dbo.DeliveryMethods [DM] ON [DM].DeliveryMethodId = [D].DeliveryMethodId
SELECT DeliveryVersionId,
Label = STUFF(
(SELECT ',' + Label FROM #TmpLabels FOR XML PATH('')), 1, 1, ''
)
FROM #TmpLabels
GROUP BY DeliveryVersionId
-- FinalResults
SELECT [O].OfferId, [O].Title, [O].OfferManager, [DL].Label AS Delivery
FROM #BasicOffers [O]
INNER JOIN #TmpLabels [DL] ON [DL].DeliveryVersionId = [O].DeliveryVersionId
I don't really know, if it's the best solution to store everything into a temporary table and then merge it or to select it all at once.
In any case unfortunately my query seems not to work correctly.
Do you have an idea on how to solve this issue?
Thanks a lot!