通过'从相关的'内部连接多个行。子查询成单个文本字符串

时间:2015-08-07 13:00:28

标签: sql sql-server group-concat correlated-subquery

之前已经提出了类似的问题,但我特别想找到一个答案来对相关的子查询做同样的事情。

我在SQL Server上这样做,我无法利用存储过程或临时表创建方法。

熟悉Client Matter账单的人;我已经制定了一个由'组成的小组。使用row_number技术查询返回每个唯一客户端的前三名执行者,在一段时间内对他们的金额求和。

这给了我这样的东西:

  clientmatterno  attorneyname  amount seq_num
  111111.00001     John Doe     $30,000 1
  111111.00001     Mark Tim     $23,000 2
  111111.00001     Jane Sue     $15,000 3
  111111.00001     Mary Ann      $5,000 4
  222221.00501     John Doe     $35,000 1
  222221.00501     David Hu     $30,000 2
  444444.00003     Shelly Y     $50,000 1

我认为,我必须首先通过分组来总结每位律师的金额,以便找到总数,从而得到正确的seq_num。
我现在尝试使用此子查询结果来进行字符串连接,以便得到以下结果:

  111111.00001     John Doe|Mark Tim|Jane Sue   
  222221.00501     John Doe|David Hu
  444444.00003     Shelly Y

我认为可以使用的查询,查看过去有关此主题的问题:

select subq.clientmatterno as [Id], 
, 
     STUFF(
         (SELECT DISTINCT ',' + subq.attorneyname
          FROM ????
          WHERE ????
          FOR XML PATH (''))
          , 1, 1, '')  AS TopPerformers
from ( 
SELECT clientmatterno, attorneyname, sum(amount), 
 row_number() over (partition by clientmatterno order by sum(amount) desc) as seq_num
FROM ...
WHERE ...
GROUP BY clientmatterno, attorneyname
) as subq
where seq_num <= 3
group by clientmatterno

我的问题是如何连接和构建STUFF功能。错误非常简单:我似乎无法使用子查询集&#39; subq&#39;在STUFF函数内的FROM子句中。
我还没有尝试过XML FOR Auto方法。

1 个答案:

答案 0 :(得分:1)

尝试使用公用表表达式而不是派生表:

with cte as (
    SELECT 
       clientmatterno, 
       attorneyname, 
       sum(amount) amount, 
       seq = row_number() over (partition by clientmatterno order by sum(amount) desc) 
    FROM ...
    WHERE ...
    GROUP BY clientmatterno, attorneyname
)

SELECT 
    clientmatterno,
    STUFF(
       (
       SELECT '|' + attorneyname
        FROM cte
        WHERE clientmatterno = a.clientmatterno
       AND seq <= 3
        FOR XML PATH ('')
       ), 1, 1, ''
    )  AS Attorneynames
FROM cte AS a
GROUP BY clientmatterno