如何过滤透视结果

时间:2013-09-06 13:37:42

标签: sql-server sql-server-2008-r2 pivot

是否可以从PIVOT结果中排除某些vaules。

引用this question我想知道是否可以排除数据透视表中具有0值的列。

想象一下,对于EventType会议,计数为0,是否可以不显示它?

1 个答案:

答案 0 :(得分:1)

我希望您已经从问题中实施了以下解决方案

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(EventType) 
                    from dbo.testTable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT year,' + @cols + ' 
            from 
            (
              select EventType, 
                  year = year(date) 
              from dbo.testTable
            ) x
            pivot 
            (
                count(EventType)
                for EventType in (' + @cols + ')
            ) p '

execute(@query)

如果是,那么你可以做以下

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(EventType) 
                    from dbo.testTable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @where = ' where ' + STUFF((SELECT distinct ' Or ' + QUOTENAME(EventType) + ' <> 0 '
                    from dbo.testTable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,2,3,'')

        set @query = 'SELECT year,' + @cols + ' 
            from 
            (
              select EventType, 
                  year = year(date) 
              from dbo.testTable
            ) x
            pivot 
            (
                count(EventType)
                for EventType in (' + @cols + ')
            ) p ' + @where


execute(@query)