this is my first attempt at dynamic pivoting in SQL and I have become a bit stuck!
I have two tables that I am joining on, one holds stock items and the other holds different prices for stock items for different websites(sources). As there is the possibility of having different sites, the query needs to be dynamic.
The problem is that I cannot remove nulls from the results and I was hoping that someone could help.
results look like this currently:
ID site-site1 site-site2 site-site3
1 null 1.99 2.99
2 12.99 null 10.00
3 1.50 null 2.00
The query is as follows:
DECLARE @sources nvarchar(max)
SELECT @sources =
STUFF(( SELECT DISTINCT ',[' +
CASE
WHEN ip.[Source] is null or ip.[Source] = '' THEN 'Default'
ELSE ip.[Source]
END
+ ' - ' +
CASE
WHEN ip.secondSource is null or ip.secondSource = '' THEN 'Default'
ELSE ip.secondSource
END
+ ']'
FROM itemprice ip
for XML PATH('')
), 1, 1, '')
DECLARE @SQL nvarchar(MAX)
SELECT @SQL = N'
SELECT *
FROM
(
SELECT
s.id,
[Source] = CASE
WHEN ip.[Source] is null or ip.[Source] = '''' THEN ''Default''
ELSE ip.[Source]
END + '' - '' +
CASE WHEN ip.secondSource is null or ip.secondSource = '''' THEN ''Default''
ELSE ip.secondSource
END,
SalePrice = isnull(ip.SalePrice, 0)
FROM stock s
LEFT OUTER JOIN itemprice ip on ip.id = s.id
) data
PIVOT
(
MAX(SalePrice) for [Source] IN (' + @sources + ')
) as PivotTable
ORDER BY PivotTable.id'
exec sp_executesql @sql
Any help would be greatly appreciated, it appears as though it is not as simple as wrapping each @sources item in an ISNULL.
Thanks
Unfortunately, you have to ISNULL each of the individual pivoted columns. Either that or CROSS JOIN your
datasubquery to generate the full matrix and perform ISNULL there.e.g. to replace NULLs with 0’s using ISNULL on pivoted columns: