【问题标题】:MSSQL How to handle null values to count them within pivotMSSQL如何处理空值以在数据透视中计算它们
【发布时间】:2021-03-27 04:03:07
【问题描述】:

我又来了,因为我遇到了另一个与空值有关的数据透视表问题。

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

但使用数据透视表(再次感谢 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

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

【问题讨论】:

  • 你是对的拉姆。对不起。我错过了这个论坛很多年了,我忘记了。请原谅我。

标签: sql sql-server count pivot sql-null


【解决方案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

【讨论】:

    猜你喜欢
    • 2013-09-14
    • 2016-12-30
    • 2016-06-14
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 2018-05-20
    相关资源
    最近更新 更多