0

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?

4

1 回答 1

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)
于 2013-09-06T13:59:08.730 回答