Tak for essensen! Så meget bedre end at trække tænder for at få skema og data. :-) Hvis du tilslutter dette til din hovedforespørgsel, skulle du se de resultater, du leder efter (nå, meget tæt på - se nedenfor).
DECLARE @SalesRepID INT, @SurgeonID INT, @LocationID INT;
SELECT @SalesRepID = 2, @SurgeonID = 1, @LocationID = 1;
;WITH x AS
(
SELECT CommissionPercent, Categories = STUFF((SELECT ', '
+ tCat.Category FROM #tCategories AS tCat
INNER JOIN #tCommissions AS tCom
ON tCat.CategoryID = tCom.CategoryID
WHERE tCom.CommissionPercent = com.CommissionPercent
FOR XML PATH, TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
FROM #tCommissions AS com
WHERE SalesRepID = @SalesRepID
AND SurgeonID = @SurgeonID
AND LocationID = @LocationID
),
y AS
(
SELECT s = RTRIM(CommissionPercent) + ' (' + Categories + ')'
FROM x GROUP BY CommissionPercent, Categories
)
SELECT Result = STUFF((SELECT ', ' + s FROM y
FOR XML PATH, TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '');
Resultatet er lidt anderledes, end du bad om, men du kan rette det ved at anvende strengformatering, når du trækker CommissionPercent.
Result
--------------------------------------------------------
0.05 (Shirts, Shoes, Dresses), 0.10 (Hats), 0.15 (Pants)