Yannick
Yannick

Reputation: 3663

SQL result as a list

I'm trying to build a sql that will return the customers for a specific invoice as a list.

To better explain myself I've attach a diagram of what I'm trying to accomplish.

enter image description here

AS you can see from the SQL Result I would like the SQL to show the customers as a list for each invoices.number

How would I accomplish the SQL (for SQL SERVER)?

Upvotes: 4

Views: 183

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138980

declare @Invoices table(ID int, Number varchar(10))
declare @Customers table(ID int, Name varchar(20))
declare @InvoiceCustomers table(InvoiceID int, CustomerID int)

insert into @Invoices values (1, 'INV01')
insert into @Customers values (1, 'NAME1'),(2, 'NAME2'),(3, 'NAME3')
insert into @InvoiceCustomers values (1, 1),(1, 2),(1, 3)

select I.Number as InvoicesNumber,
       stuff((select ', '+C.Name
              from @Customers as C
                inner join @InvoiceCustomers as IC
                  on C.ID = IC.CustomerID
              where IC.InvoiceID = I.ID
              for xml path(''), type).value('.', 'varchar(max)'), 1, 2, '') as CustomersName
from @Invoices as I

Upvotes: 3

Related Questions