简体   繁体   English

sql:列中类型的百分比

[英]sql: percentage of a type in a column

I'm trying to get percentage of missed calls for each user, so I used the following sql query: 我试图获取每个用户未接来电的百分比,因此我使用了以下sql查询:

select distinct a__contact
       , count (case when a__type = 'missed' 
                     then 1 else 0 end) / count(*) * 100 
                                                  as "percentage of missed calls"

from table
group by 1

However, for each user I got 100 which do not seem to be correct output at all. 但是,对于每个用户,我得到了100个,这似乎根本不是正确的输出。 Could someone help me to identify the error in my query? 有人可以帮助我确定查询中的错误吗? thank you so much! 非常感谢!

Here is a simpler way to express the logic you want: 这是一种表达所需逻辑的简单方法:

select a__contact,
       avg(case when a__type = 'missed' then 100.0 else 0 end) as percentage_missed_calls
from table
group by 1;

Your version is failing because you are using count() in the numerator. 您的版本失败,因为您正在分子中使用count() You really intend sum() . 你真的打算sum() count() counts the number of non- NULL values and both "1" and "0" are non- NULL . count()计算非NULL值的数量,并且“ 1”和“ 0”均为非NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM