将多张发票组合在一起

时间:2013-03-07 15:12:41

标签: sql sql-server

一次付款可以有多个发票,因此查询表或结果集可能会带回多行。

如何阻止此事?

Customer Name   Payment no   Invoice No
-------------   ----------   ----------    
Dave A          1            10
Dave T          2            10
Dave T          2            12

所以我想:

Customer Name   Payment no   Invoice No
-------------   ----------   ----------    
Dave A          1            10
Dave T          2            10, 12

1 个答案:

答案 0 :(得分:3)

SELECT
     [Customer Name], [Payment no],
     STUFF(
         (SELECT ',' + CAST([Invoice No] AS VARCHAR(10))
          FROM TableName
          WHERE [Customer Name] = a.[Customer Name] AND
                [Payment no] = A.[Payment no]
          FOR XML PATH (''))
          , 1, 1, '')  AS InvoiceList
FROM TableName AS a
GROUP BY [Customer Name], [Payment no]