首页 > 解决方案 > 在 CASE + SUM 中显示空值

问题描述

我有一个具有以下结构的表:

CREATE TABLE [dbo].[TESTING](
    [ID] [nvarchar](2) NULL,
    [TYPE] [nvarchar] (1) NULL,
    [TIME] [int] NULL

并使用以下数据:

INSERT INTO [dbo].[TESTING]
           ([ID]
           ,[TYPE]
           ,[TIME])
     VALUES
('A1','1',3),
('A1','1',6),
('A2','2',8),
('A2','2',9),
('B1','1',2),
('B1','1',6),
('B2','2',4),
('B2','2',8),
('B2','2',11),
('B2','2',12)

我想做的就是这个。我想创建一个列,如果TIME小于或等于 5,则接收值“<= 5”,如果 TIME 大于 5,则接收值“>5

然后我提出以下声明:

select ID,  TYPE, 
(case when TIME <= 5 then '<= 5' 
when TIME > 5 then '> 5' 
else 'OTHER' end) AS CONDITION, 
SUM(TIME) TOTAL 
from [dbo].[TESTANDO] 
GROUP BY ID, TYPE,
(case when TIME <= 5 then '<= 5' 
when TIME > 5 then '> 5' 
else 'OTHER' end)

结果:

在此处输入图像描述

我希望除了出现的数据之外,如果有“<= 5 or> 5”没有值的值,我会用TOTAL 0 来的行。在示例中我没有行来自满足条件“<= 5”的 A2 组,该条件应出现在结果中,列TOTAL = 0

像这样:

在此处输入图像描述

标签: sqlsql-server-2008conditionalcase

解决方案


用于cross join生成行,然后使用left join聚合来填充值:

select i.id, i.type, c.condition, coalesce(sum(time), 0) as total
from (select distinct id, type from testing) i cross join
     (values ('<= 5'), ('> 5')) c(condition) left join
     testing t
     on t.id = i.id and
        t.type = i.type and
        ((condition = '<= 5' and time <= 5) or
         (condition = '> 5' and time > 5)
        )
group by i.id, i.type, c.condition
order by i.id, i.type, c.condition;

是一个 db<>fiddle。


推荐阅读