在 CASE + SUM 中显示空值

Show null values ​in CASE + SUM

我有一个 table 结构如下:

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)

我想做的就是这个。我想创建一个接收值“<= 5”的列,如果 TIME 小于或等于 5 或​​“> 5”,如果 TIME 大于 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 或> 5”没有值,我附带的行 TOTAL 0. 在这个例子中,我没有满足条件“<= 5”的组 A2 的行,它们应该出现在结果中,列为 TOTAL = 0

像这样:

使用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;

Here 是一个 db<>fiddle.