You need to join the two tables in the source section of your pivot - your sub-query
x
above.
You also need to remove all of the
WHERE
clauses where you are limiting the
salesid = 1
Because of that you also need to use
DISTINCT
on the generation of the column list, which means you also need to change the
ORDER BY
on that section - I've used the shortcut
ORDER BY 1
instead of
ORDER BY ',' + QUOTENAME(taxname)
This query gets pretty close to your expected results, it's not exact because the sample data given doesn't match your expected results:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(taxname)
from TaxDetails
group by taxname, taxid
order by 1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT salesid, invno, ' + @cols + N' from
(
select T.salesid, invno, T.amount, taxname
from SalesDetails S
LEFT OUTER JOIN TaxDetails T ON T.salesid = S.salesid
) x
pivot
(
max(amount)
for taxname in (' + @cols + N')
) p ORDER BY Salesid'
exec sp_executesql @query;