SQL结果作为列表

时间:2011-11-02 16:09:15

标签: sql sql-server

我正在尝试构建一个sql,它会将特定发票的客户作为列表返回。

为了更好地解释自己,我附上了一份我想要完成的图表。

enter image description here

从SQL结果中我可以看到,我希望SQL将客户显示为每个发票的列表。数字

我如何完成SQL(对于SQL SERVER)?

1 个答案:

答案 0 :(得分:3)

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