0

One payment can have more than one invoice, so querying table or result set may bring back more than one row.

How do I stop this ?

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

So I want:

Customer Name   Payment no   Invoice No
-------------   ----------   ----------    
Dave A          1            10
Dave T          2            10, 12
Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
James Khan
  • 773
  • 2
  • 18
  • 46

1 Answers1

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]
John Woo
  • 258,903
  • 69
  • 498
  • 492