对于要将 NULL 替换为 0 的列,请使用ISNULL函数:
ISNULL(dynamicColumn1, 0)
对于列 [0],您可以使用COALESCE函数:
COALESCE(dynamicColumn1, dynamicColumn2, etc)
动态声明
DECLARE @PivotColumnHeadersForSelect varchar(max),
@PivotColumnHeadersForPivot varchar(max)
SELECT @PivotColumnHeadersForSelect =
COALESCE(@PivotColumnHeadersForSelect + CASE WHEN [mPriceKW] = 0.00 THEN '[0.00]' ELSE ',ISNULL(['
+ CAST([mPriceKW] as varchar(10)) + '], 0.0) AS [' + CAST([mPriceKW] as varchar(10)) + ']' END,
+ CASE WHEN [mPriceKW] = 0.00 THEN '[0.00]' ELSE 'ISNULL([' + CAST([mPriceKW] as varchar(10))
+ '], 0.0) AS [' + CAST([mPriceKW] as varchar(10)) + ']' END),
@PivotColumnHeadersForPivot =
COALESCE(@PivotColumnHeadersForPivot + ',[' + CAST([mPriceKW] as varchar(10)) + ']',
+ '[' + CAST([mPriceKW] as varchar(10)) + ']')
FROM PivotColumn
GROUP BY [mPriceKW]
ORDER BY [mPriceKW] ASC
SET @PivotColumnHeadersForSelect =
REPLACE(@PivotColumnHeadersForSelect, '[0.00]', 'COALESCE(' + @PivotColumnHeadersForPivot + ') AS [0.00]')
--SELECT @PivotColumnHeadersForSelect, @PivotColumnHeadersForPivot
DECLARE @PivotTableSQL NVARCHAR(MAX)
SET @PivotTableSQL = N'
IF OBJECT_ID(''tempdb.dbo.##MyTable'') IS NOT NULL DROP TABLE dbo.##MyTable
SELECT *
INTO dbo.##MyTable
FROM (SELECT dFrom, dTo, ' + @PivotColumnHeadersForSelect + '
FROM (
SELECT a.dFrom, a.dTo ,a.[mPriceKW] , a.fQuantumMW
FROM PivotColumn a
WHERE a.iBid = 1
) TableDate
PIVOT (min(fQuantumMW) FOR [mPriceKW] IN (' + @PivotColumnHeadersForPivot + ')
) PivotTable) dt '
--PRINT @PivotTableSQL
EXECUTE(@PivotTableSQL)
SELECT *
FROM ##MyTable
另请参阅SQLfiddle上的演示