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 のデモも参照してください