I'm running into an issue where the output for my dynamic pivot contains thousands of NULL values that I would like to replace with 0. I am not able to use ISNULL before the pivot is generated because there aren't any NULL values in the original table. I've searched everywhere and I havn't located anything that works for me. Here is my code.
DECLARE @col NVARCHAR(MAX);
DECLARE @sql NVARCHAR(MAX);
SET @col = (SELECT STRING_AGG(CONVERT(NVARCHAR(MAX),CONCAT('[',[order_date],']')),',') FROM
(
SELECT DISTINCT TOP 10000 (CAST(CONVERT(datetimeoffset,[purchase-date],127) AS DATE)) AS order_date
FROM dbo.Amazon_FBAFulfilledShipments_Report
ORDER BY order_date ASC
) trial_table);
SELECT @col
PRINT @col
SET @sql =
'SELECT ship_country,sku,' + @col + '
FROM
(
SELECT [ship-country] AS ship_country,sku,CAST([quantity-shipped] as INT) AS quantity_shipped,CAST(CONVERT(datetimeoffset,[purchase-date],127) AS DATE) AS order_date
FROM dbo.Amazon_FBAFulfilledShipments_Report
) as Source_table
PIVOT
(SUM(quantity_shipped) FOR order_date IN (' + @col +')
)AS pivot_table'
PRINT @sql
EXECUTE (@sql)