How to filter pivot results

*爱你&永不变心* 提交于 2019-12-11 23:30:03

问题


Is it possible to exclude some vaules from the PIVOT results.

Referencing this question i would like to know if it is posible to exclude the columns in the Pivot table that has 0 value.

Imagine there is a count of 0 for EventType Meeting, is it possible not to show it at all?


回答1:


i hope you have implemented following solution from the question

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)

if so then you can do following

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)


来源:https://stackoverflow.com/questions/18659203/how-to-filter-pivot-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!