sql >> Database >  >> RDS >> Sqlserver

Null-waarden vervangen in dynamische spil-sql-query

U moet een andere kolomlijst genereren voor de select-instructie en individuele maanden inpakken met ISNULL, zoals zo:

DECLARE @cols AS NVARCHAR(MAX),
        @selectCols AS NVARCHAR(MAX),
        @query AS NVARCHAR(MAX) 

SELECT  @selectCols = STUFF
(
(
SELECT distinct ', ISNULL(' + QUOTENAME([MONTH]) + ', 0) AS ' + QUOTENAME([MONTH])
FROM   [HEADCOUNT]
WHERE  [MONTH] BETWEEN '01-012018' AND '12-01-2018'
ORDER BY ',' + QUOTENAME([MONTH])
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''
)



SELECT  @cols = STUFF
(
(
SELECT distinct ',' + QUOTENAME([MONTH])
FROM   [HEADCOUNT]
WHERE  [MONTH] BETWEEN '01-012018' AND '12-01-2018'
ORDER BY ',' + QUOTENAME([MONTH])
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''
)
SET     @query = 'SELECT [FTE/RATE CARD],' + @selectCols + ' FROM
(
SELECT  [MONTH],[FTE/RATE CARD],[HC]
FROM    [HEADCOUNT]
WHERE   [CC-LOC] IN ([CC-LOC]) 

) x pivot (Sum ([HC]) for [MONTH] in (' + @cols + '))p' execute(@query)



  1. Associatieve array op pakketniveau maken in java

  2. Hoe zou u sequenties implementeren in Microsoft SQL Server?

  3. Maak verbinding met MySQL met JDBC via het netwerk

  4. MariaDB POWER() uitgelegd