MSSQL 如何处理空值以在数据透视表中对它们进行计数

MSSQL How to handle null values to count them within pivot

我又来了,因为我还有另一个与空值有关的枢轴问题 table。

IF OBJECT_ID(N'tempdb..#exams') IS NOT NULL
BEGIN
DROP TABLE #exams
END
GO


create table #exams (
id uniqueidentifier,
exam nvarchar(max),
technician nvarchar(max)
)



insert into #exams 
values 
(newid(),'Esame1','Tecnico1'),
(newid(),'Esame2','Tecnico1'),
(newid(),'Esame1','Tecnico2'),
(newid(),'Esame3','Tecnico1'),
(newid(),'Esame3','Tecnico2'),
(newid(),'Esame3','Tecnico3'),
(newid(),'Esame3','Tecnico1'),
(newid(),'Esame1',NULL)

我必须以某种方式处理报告中的空值。

对于 sum case 子句,我可以这样简单地做:

 select
 exam,
 sum(case when technician = 'Tecnico1' then 1 else 0 end) as Tecnico1,
 sum(case when technician = 'Tecnico2' then 1 else 0 end) as Tecnico2,
 sum(case when technician = 'Tecnico3' then 1 else 0 end) as Tecnico3,
 sum(case when technician is null then 1 else 0 end) as Unknown 
 from #exams
 group by exam
 order by exam
exam Tecnico1 Tecnico2 Tecnico3 Unkwnon
Esame1 1 1 0 1
Esame2 1 0 0 0
Esame3 2 1 1 0

但使用枢轴 table(再次感谢 Tole1010)空值位于我的枢轴之外

select * from (
    select id,exam,
           technician 
           from #exams
    ) as t
    pivot 
    (   count(id)
            for technician in (Tecnico1,Tecnico2,Tecnico3)
        ) as t

我只得到:

exam Tecnico1 Tecnico2 Tecnico3
Esame1 1 1 0
Esame2 1 0 0
Esame3 2 1 1

有没有办法添加一个列来使用数据透视语法计算那些空值?

您通常会将 null 替换为其他不会出现在列中的内容:

select * from (
    select id, exam,
       coalesce(technician , 'Unknown') as technician
    from #exams
) as t
pivot (   
    count(id)
    for technician in (Tecnico1,Tecnico2,Tecnico3, Unknown)
) as t

Demo on DB Fiddlde:

exam Tecnico1 Tecnico2 Tecnico3 Unknown
Esame1 1 1 0 1
Esame2 1 0 0 0
Esame3 2 1 1 0