sql - 根据每个 id 中存在的字段值计算计数:MSSQL
问题描述
我有如下数据
id desc
1 error 1
1 captured
1 closed
2 captured
2 closed
3 closed
预期输出是:对于每个 id,如果有描述“错误 1”,它应该在 A 组中计数,否则在 B 组中。
A B
1 2
到目前为止,我的查询是检查一个上面和一个下面。
select sum(A) as TW, sum(B) as B
from (
select
case when lower(Description) like '%error 1%' then 1 end as A,
case when lg_description not like '%error 1%'
and ld_desc not like '%error 1%'
then 1 end as B
from (
select Description,
lag(Description)
over (partition by DSurveillanceAssetFaultID order by TimestampUTC) as lg_description,
lead(Description)
over (partition by DSurveillanceAssetFaultID order by TimestampUTC) as ld_desc
from #temp1) a
)b
group by Format(TimestampUTC, 'MMMM-yyyy')
解决方案
使用条件聚合:
select count(distinct case when description = 'error 1' then id end) as A
count(distinct id)
- count(distinct case when description = 'error 1' then id end) as B
from your_Table t
推荐阅读
- css - 如何在第一个 div 的末尾开始第二个 div。?
- javascript - 在时间线 GSAP 中对补间进行分组
- java - 用一行代码在 Kotlin 中设置 Android 屏幕亮度(相对于 Java)
- c# - Microsoft Graph API - 更新现有组
- java - Java 的 add-opens 似乎无法使包可访问
- python - 如何在python中先合并然后裁剪栅格
- r - 计算 R 中子字符串的实例
- virtualbox - 如何解决虚拟盒子上的“VT-x 不可用(VERR_VMX_NO_VMX)”错误?
- ruby-on-rails - 用于has_many关联的Rails嵌套属性“没有将符号隐式转换为整数”
- java - 为什么我的 Spring Boot APP 在 Heroku 中部署后没有出现