Show NULL value as pivoted column in SQL Server -
i need pivot count of values matches "animal type" in code sample below. unfortunately may missing records in col2 ('a','b'), need count animal type in 'a','b', or null. need pivot null
column count value. doing sum across pivoted columns @ end of query, , null values in col2 not match total.
declare @testdata table ( col1 varchar(10) , col2 varchar(10) ) insert @testdata values ('dog','a') insert @testdata values ('cat','b') insert @testdata values ('rabbit',null) select * @testdata select pvt.col1 [animal type] , pvt.a [a] , pvt.b [b] , total.records [total count] ( select col1 , col2 , count(*) records @testdata group col1 , col2 ) s pivot ( sum(records) col2 in ([a], [b]) ) pvt join ( select col1 , count(*) records @testdata group col1 ) total on pvt.col1 = total.col1
modify col2 in subquery isnull function shown below:
select pvt.col1 [animal type] , pvt.a [a] , pvt.b [b] , pvt.[null] [null] , total.records [total count] ( select col1 , isnull(col2,'null') col2 , count(*) records @testdata group col1 , col2 ) s pivot ( sum(records) col2 in ([a], [b], [null]) ) pvt join ( select col1 , count(*) records @testdata group col1 ) total on pvt.col1 = total.col1