sql - 捕获 null 的总和
问题描述
如何按日期和公司捕获属性(bit_id)的空值总和
解决方案
如果您的意思是您想计算每个日期/公司有多少个值NULL
,那么您可以使用CASE
包含在 a 中的语句SUM
:
declare @dataTable table (
recordDate date,
company varchar(100),
attribute bit
)
insert into @dataTable values
('2021-09-28','CompanyA',null),
('2021-09-28','CompanyA',null),
('2021-09-28','CompanyA',1),
('2021-09-28','CompanyB',0),
('2021-09-28','CompanyB',null),
('2021-09-29','CompanyA',0),
('2021-09-29','CompanyB',1),
('2021-09-29','CompanyA',null),
('2021-09-29','CompanyB',null),
('2021-09-29','CompanyB',null),
('2021-09-29','CompanyB',null)
select
recordDate,
company,
sum(case when attribute is null then 1 else 0 end) as countNULLs
from @dataTable
group by recordDate, company
order by recordDate, company
结果:
/------------------------------------\
| recordDate | company | countNULLs |
|------------|----------|------------|
| 2021-09-28 | CompanyA | 2 |
| 2021-09-28 | CompanyB | 1 |
| 2021-09-29 | CompanyA | 1 |
| 2021-09-29 | CompanyB | 3 |
\------------------------------------/
推荐阅读
- css - 如何添加框阴影效果,仅对 div 的边框?
- python - SCDL 故障排除
- laravel - 如何检查 laravel 控制器中的请求字段是否为空?
- php - 教义:仅使用 id 来设置相关实体
- javascript - React TypeError:在路由器上解构不可迭代实例的尝试无效
- mule - mule 中默认标头的概念
- android - 约束布局中的动态高度对齐
- elasticsearch - 按字段的最小值搜索文档
- java - Spring Boot 应用程序可以向自身发出 HTTP 请求吗?
- java - @Deprecated 与 @Deprecated() 有什么区别?