在CASE + SUM中显示空值

时间:2019-04-29 19:44:56

标签: sql sql-server-2008 conditional case

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

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)

结果:

enter image description here

除了显示的数据外,我还希望有一些值,其中“ <= 5或> 5”没有值我随 TOTAL 0。在示例中,我没有来自组A2的满足条件“ <= 5”的行,该行应出现在结果中,列 TOTAL = 0

像这样:

enter image description here

1 个答案:

答案 0 :(得分:1)

使用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 <>小提琴。