将行值连接到每个组的单行

时间:2015-09-23 12:55:26

标签: sql sql-server sql-server-2014

我有问题。

表-1名称:InvoiceDetail

InvoiceNo      StockCode       Piece
----------     -----------     ------
1                CP-001          10
1                CP-002          15
2                CP-001          18
2                MN-001          18

表-2名称:股票

StockCode       StockName
-----------     -----------
CP-001          Computer-A
CP-002          Computer-B
MN-001          Monitor-A

预期结果

InvoiceNo      Description                   TotalPiece
----------     -----------------------       ----------
1              Computer-A, Computer-B            25
2              Computer-A, Monitor-A             36

我写了以下查询

查询

SELECT InvoiceNo, 
       (select StockName + '-' from Stock
    where StockCode = Results.StockCode
    order by StockName 
    FOR XML PATH('')) AS Description,
    SUM(Piece) AS TotalPiece
FROM InvoiceDetail Results
GROUP BY InvoiceNo, Results.StockCode
ORDER BY InvoiceNo

结果

InvoiceNo   Description TotalPiece
1           Computer-A- 10
1           Computer-B- 15
2           Computer-A- 18
2           Monitor-A-  18

怎么了?

1 个答案:

答案 0 :(得分:1)

在CTE中单独执行group by,然后您可以安全地将描述连接为一个单独的步骤:

with InvoiceGroupings as (
  select t.InvoiceNo,
         sum(t.Piece) as TotalPiece
    from InvoiceDetail t
   group by t.InvoiceNo)
select g.InvoiceNo,
       stuff((select ', ' + s.StockName
               from InvoiceDetail i
               join Stock s
                 on i.StockCode = s.StockCode
              where i.InvoiceNo = g.InvoiceNo
              order by s.StockName
                for xml path('')),1,2,'') as Description,
       g.TotalPiece
  from InvoiceGroupings g
 order by g.InvoiceNo

SQL Fiddle Demo