sql语句for xml path

现有发票表Invoice  存有字段发票号 InvoiceCode

发票子表InvoiceSub

任务单表PrjTask

其关系为  Invoice 与 InvoiceSub 是 1 对 n , InvoiceSub 与 PrjTask 是 n 对 1

现要求任务单对应的发票号 多个以逗号分开

select PrjTaskId,InvoiceCode=stuff(

(

	select ',' + InvoiceCode 

	from

	(

		select a.PrjTaskId,b.InvoiceCode

			from InvoiceSub  a

			left join Invoice b on a.InvoiceId=b.Id

	) c 

	where c.PrjTaskId = d.PrjtaskId for xml path('')

),1,1,'')

from InvoiceSub d 

group by d.PrjTaskId

 其中stuff为把第一个逗号去掉

你可能感兴趣的:(sql语句)