sql - 在 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
像这样:
解决方案
用于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。
推荐阅读
- c# - 找不到配置绑定扩展“system.serviceModel/bindings/bsicMttpBinding”
- java - 切换大小写或不同的 URL?我应该在 Springboot 控制器中使用什么来调用不同的服务
- python - Python列表和元组解包
- mysql - 有条件地加入三个表
- python - 有没有办法从 blob url 下载 WhatsApp 网络图像,而不是单击下载按钮?
- apache-kafka - WSO2 Integration Studio v6.5.0 的内置 Kafka 模板抛出 NoClassDefFoundError
- openshift - OKD(Openshift origin)可以用于生产级集群吗?
- wordpress - 为商店分页添加重写规则
- xamarin - 如何防止 MasterDetailPage 顶部的附加导航栏(Android 上的 Xamarin)
- python-3.x - 调用 cv2.findContours() 时出现“ValueError: no enough values to unpack”