I have the following TSQL that I have been trying, without luck, to do 2 things with:
- convert Nulls to 0
- output to a temporary table I can use for other operations.
Part of the result is captured in the attached:
What changes do I need to make to both capture the result into a temp table with dynamic columns, and eliminate the nulls? Thanks.
DECLARE @cols NVARCHAR(MAX), @stmt NVARCHAR(MAX), @ParmDefinition NVARCHAR(MAX), @PVT3 NVARCHAR(MAX);
--Get distinct values of the PIVOT Column
SELECT @cols = ISNULL(@cols+', ', '')+'['+T.Cat+']'
FROM
(
SELECT TOP 100 CONVERT( VARCHAR(2), IncomeCategoryID) AS Cat
FROM Payroll.lu_IncomeCategory
WHERE IsAllowance <> 0
AND IncomeCategoryID IN
(
SELECT DISTINCT
IncomeCategoryID
FROM Payroll.Income
WHERE IncomeCategoryID <> 0
)
ORDER BY IncomeCategoryID
) AS T;
SELECT @stmt = N'
SELECT *
FROM (SELECT EmployeeID,IncomeCategoryID,
SUM(RateAmount) [Amount]
FROM Payroll.Income
GROUP BY EmployeeID, IncomeCategoryID ) as PayData
pivot
(
SUM([Amount])
FOR IncomeCategoryID IN ('+@cols+')
) as IncomePivot';
EXEC sp_executesql
@stmt = @stmt;