如何从SQL数据透视表中删除Null值

时间:2019-09-10 11:32:59

标签: sql-server pivot

我一直在尝试从数据透视表中删除NULL值。我尝试了几种建议的解决方案,以免碰运气。

    Declare @toName as nvarchar(max)

    SELECT *
    FROM (SELECT 
    isnull(protocol,0) as Protocol,     
    isnull(callCategory,0) as DCRCategory,
    isnull(DATEPART(Year, eCreationTime),0) AS Year, 
    isnull(DATENAME(MONTH, eCreationTime),0) [Month],
    isnull(COUNT(1),0) callCategory

    FROM DCR_DATA
    where ProjectManager = ''' + @toName + '''
    GROUP BY protocol, callCategory, YEAR(eCreationTime), DATENAME(MONTH, eCreationTime)) 


AS MontlyDCRData

PIVOT(SUM(callCategory)   
FOR Month IN ([January],[February],[March],[April],[May],
[June],[July],[August],[September],[October],[November],
[December])) AS MNamePivot

以下是我返回的示例: enter image description here

Protocol    DCRCategory Year    January February    March   April   May     June    July    August  September   October November    December
123         Cat 1       2017    NULL    NULL        NULL    NULL    NULL    NULL    NULL    NULL    4           NULL    NULL        NULL

2 个答案:

答案 0 :(得分:1)

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

SELECT @cols = STUFF((SELECT ',' + QUOTENAME(+'ISNULL('+CAST(ColName AS VARCHAR) +' ,0)'  ) + ' ' + QUOTENAME(ColName)
                    FROM TblName
                    GROUP BY ColName
                    ORDER BY ColName
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


SELECT @cols1 = STUFF((SELECT ',' +  QUOTENAME(ColName)
                    from TblName
                    group by ColName
                    order by ColName
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


SET @query = 'SELECT ColName1,' + @cols + ' from 
             (
                SELECT ColName1, ColName2, ColName3
                FROM TblName
            ) x
            PIVOT 
            (
                SUM(ColName3)
                FOR ColName2 IN (' + @cols1 + ')
            ) p '

EXECUTE(@query);

答案 1 :(得分:0)

这不是最优雅的解决方案,但是->选择一个临时表

Declare @toName as nvarchar(max)

SELECT *
INTO #tmpTable
FROM (SELECT isnull(protocol,0) as Protocol
        , isnull(callCategory,0) as DCRCategory
        , isnull(DATEPART(Year, eCreationTime),0) AS Year
        , isnull(DATENAME(MONTH, eCreationTime),0) [Month]
        , isnull(COUNT(1),0) callCategory

    FROM DCR_DATA
    where ProjectManager = ''' + @toName + '''
    GROUP BY    protocol
    ,           callCategory
    ,           YEAR(eCreationTime)
    ,           DATENAME(MONTH, eCreationTime))


    AS MontlyDCRData

    PIVOT(SUM( callCategory)
    FOR Month IN ([January],[February],[March],[April],[May],
    [June],[July],[August],[September],[October],[November],
    [December])) AS MNamePivot

然后从那里开始为空。

SELECT tmp.Protocol, tmp.DCRCategory, tmp.[Year]
    , isnull(tmp.January,0)
    , ... 
    , isnull(tmp.December,0)
FROM #tmpTable as tmp