SQL Server PIVOT - 将空值删除为0

时间:2017-03-30 04:00:05

标签: sql-server tsql

非常快速的问题,我想删除空值,当我尝试在@strQuery中添加ISNULL(LoanAmount, 0)时,它会给我一个错误。对我来说,删除那些空值并将其替换为0,

非常重要

这是我的代码:

DECLARE @LoanTypeDesc AS NVARCHAR(MAX),
    @strQuery  AS NVARCHAR(MAX),
    @strColumn AS NVARCHAR(MAX)

SELECT @LoanTypeDesc = STUFF((SELECT ',' + QUOTENAME(lt.[Description]) 
                FROM LoanType lt
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

SET @strQuery = 'SELECT *
FROM (
SELECT TOP 1000 EmployeeID,
    LoanAmount,
    lt.[Description]
FROM LoanContract lc
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
ORDER BY EmployeeID ASC
) src
PIVOT(
SUM(LoanAmount)
FOR Description IN (' + @LoanTypeDesc + ')
) piv;'

EXECUTE (@strQuery)

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

这将删除空值。我在@SELECT_COLUMNS中创建了处理NULL的Pivoted列列表。如果您愿意,可以将EmployeeID之类的任何其他列添加到@SELECT_COLUMNS

DECLARE @LoanTypeDesc AS NVARCHAR(MAX),
    @strQuery  AS NVARCHAR(MAX),
    @strColumn AS NVARCHAR(MAX)

--Creating column list with appending ISNULL
DECLARE @SELECT_COLUMNS VARCHAR(MAX)='';
SELECT @SELECT_COLUMNS = @SELECT_COLUMNS+ 'ISNULL( '+ QUOTENAME(lt.[Description])  +',0),'
                FROM LoanType lt
SELECT @SELECT_COLUMNS= SUBSTRING(@SELECT_COLUMNS,1,LEN(@SELECT_COLUMNS)-1);


SELECT @LoanTypeDesc = STUFF((SELECT ',' + QUOTENAME(lt.[Description]) 
                FROM LoanType lt
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

--Making Select columns from @SELECT_COLUMNS instead of *
SET @strQuery = 'SELECT '+@SELECT_COLUMNS +' 
FROM (
SELECT TOP 1000 EmployeeID,
    LoanAmount,
    lt.[Description]
FROM LoanContract lc
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
ORDER BY EmployeeID ASC
) src
PIVOT(
SUM(LoanAmount)
FOR Description IN (' + @LoanTypeDesc + ')
) piv;'

EXECUTE (@strQuery)