我有一个下表类似的表
eventType. deviceModel. deviceType
received S8 Samsung
success. S8 Samsung
failure S8 Samsung
.
.
.
received = indicates that 'A' event was received
Success = indicates that 'A' event was processed successfully
failure = indicates that 'A' event failed to process
我想聚合此数据并计算deviceType和deviceModel组合的失败百分比。
基本上,我需要首先为特定的deviceModel和deviceType计数具有eventType“ received”的所有条目。
然后对相同的deviceModel和deviceType组合计数所有eventType为“成功”的条目,然后计算(接收的总数-成功的总数)/时间总数* 100的百分比。
如何使用SQL查询来做到这一点?
我希望输出类似
deviceType. deviceModel. Failure %
samsung S8 10%
答案 0 :(得分:0)
这是您想要的吗?
select deviceModel, deviceType,
avg( case when eventType = 'received' then 1.0 else 0 end ) as received_ratio
from t
where eventType in ('received', 'success')
group by deviceModel, deviceType;
这是逻辑吗?
select deviceModel, deviceType,
sum(case when eventType = 'received' then 1
when eventType = 'success' then -1
else 0
end ) / count(*) as received_ratio
from t
group by deviceModel, deviceType;
这些都不考虑“失败”,但是您似乎要其中之一。
编辑:
如果您想要失败的比例,那就是:
select deviceModel, deviceType,
avg( case when eventType = 'failure' then 1.0 else 0 end ) as failure_ratio
from t
group by deviceModel, deviceType;
答案 1 :(得分:0)
那将是:
col=val