Concatenate multiple rows from multiple tables

前端 未结 2 1283
后悔当初
后悔当初 2021-01-07 06:02

I\'ve reviewed many other posts on here and have become pretty familiar with the Coalesce function, but I haven\'t been able to figure out how to do this specific task.

2条回答
  •  [愿得一人]
    2021-01-07 07:03

    Thank you for the gist! So much better than pulling teeth to get schema and data. :-) If you plug this in to your gist query you should see the results you're after (well, very close - see below).

    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, '');
    

    The result is slightly different than you asked for, but you could fix that by applying string formatting when pulling CommissionPercent.

    Result
    --------------------------------------------------------
    0.05 (Shirts, Shoes, Dresses), 0.10 (Hats), 0.15 (Pants)
    

提交回复
热议问题