在 SQL 服务器中将 NULL 值显示为透视列
Show NULL value as pivoted column in SQL Server
我需要在我下面的代码示例中将与 "animal type" 匹配的值的计数作为主元。不幸的是,我可能缺少 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
使用 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
我需要在我下面的代码示例中将与 "animal type" 匹配的值的计数作为主元。不幸的是,我可能缺少 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
使用 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