Dynamic Pivot Example

Below is the reference code on how to create Dynamic Pivot query :

create table Cust (custname varchar(20),invoiceno varchar(20),amount int)
Insert into Cust
Values ('aa','inv1',100)

Create table TESTCU (custname varchar(20),invoiceno varchar(20),itemno int,Accountno varchar(20))

Insert into TESTCU
VALUES ('aa','inv1',1,'act1'),

declare @List varchar(200)

select @List =
STUFF((Select distinct ','+quotename(Accountno)
FOR XML PATH('')),1,1,'')

declare @SQL nvarchar(2000)
set @SQL ='Select B.*,A.amount from CUST A INNER JOIN
(select * from (select custname,invoiceno,Accountno,1 as TR from TESTCU) PT PIVOT (MIN(TR) FOR ACCOUNTNO in (' +@LIST+')) as PS) B
ON B.invoiceno=A.invoiceno'

Execute SP_Executesql @SQL