Terima kasih untuk intinya! Jauh lebih baik daripada mencabut gigi untuk mendapatkan skema dan data. :-) Jika Anda memasukkan ini ke kueri inti Anda, Anda akan melihat hasil yang Anda cari (well, sangat dekat - lihat di bawah).
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, '');
Hasilnya sedikit berbeda dari yang Anda minta, tetapi Anda dapat memperbaikinya dengan menerapkan pemformatan string saat menarik CommissionPercent.
Result
--------------------------------------------------------
0.05 (Shirts, Shoes, Dresses), 0.10 (Hats), 0.15 (Pants)