【问题标题】:Show null values ​in CASE + SUM在 CASE + SUM 中显示空值
【发布时间】:2019-04-29 19:44:55
【问题描述】:

我有一个结构如下的表:

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,我想创建一个接收值“

然后我把下面的语句:

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”没有值的值我来的行TOTAL 0. 在示例中,我没有 A2 组中满足条件“TOTAL = 0

的结果中

像这样:

【问题讨论】:

  • 请在问题中以文本表格的形式显示您想要的结果,并确保它们与您提供的数据相对应。
  • 修改后的戈登

标签: sql sql-server-2008 conditional case


【解决方案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 是一个 dbfiddle。

【讨论】:

  • 非常感谢戈登!只有一件事,如果我想放在哪里,这是个问题?喜欢.. 其中类型 = 1
  • @ClaytonTosatti 。 . .将条件放在i 的子查询中。
猜你喜欢
  • 2021-08-25
  • 2017-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
相关资源
最近更新 更多