在SQL Server中将NULL值显示为透视列

时间:2015-04-09 19:55:57

标签: sql-server null pivot

我需要在下面的代码示例中调整与“动物类型”匹配的值的计数。不幸的是,我可能会丢失col2中的记录('a','b'),但我需要计算它们在'a','b'或null中的动物类型。我需要将NULL转换为具有该计数值的另一列。我在查询结尾处对所有透视列进行求和,而col2中具有空值的那些列与总数不匹配。

declare @testData   table   (   col1    varchar(10)
                            ,   col2    varchar(10)
                            )

insert into @testData   
values ('dog','a')
insert into @testData   
values ('cat','b')
insert into @testData   
values ('rabbit',null)

select * from @testData

select  
    pvt.col1        as  [Animal Type]
,   pvt.a           as  [A]
,   pvt.b           as  [B]
,   total.records   as  [Total Count]
from    (
            select 
                col1
            ,   col2
            ,   count(*)    as  records
            from    @testData   
            group by
                col1
            ,   col2
        )   as  s
pivot
        (
            sum(records)
            for     col2 in ([a], [b])
        )   as  pvt
join    (
            select 
                col1    
            ,   count(*)    as  Records
            from    @testData
            group by
                col1
        )   as  total               on  pvt.col1 = total.col1   

1 个答案:

答案 0 :(得分:2)

使用isnull函数修改子查询中的col2,如下所示:

select  
    pvt.col1        as  [Animal Type]
,   pvt.a           as  [A]
,   pvt.b           as  [B]
,   pvt.[NULL]      as  [NULL]
,   total.records   as  [Total Count]
from    (
            select 
                col1
            ,   ISNULL(col2,'NULL') col2
            ,   count(*)    as  records
            from    @testData   
            group by
                col1
            ,   col2
        )   as  s
pivot
        (
            sum(records)
            for     col2 in ([a], [b], [NULL])
        )   as  pvt
join    (
            select 
                col1    
            ,   count(*)    as  Records
            from    @testData
            group by
                col1
        )   as  total               on  pvt.col1 = total.col1