[英]sql: percentage of a type in a column
我試圖獲取每個用戶未接來電的百分比,因此我使用了以下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
但是,對於每個用戶,我得到了100個,這似乎根本不是正確的輸出。 有人可以幫助我確定查詢中的錯誤嗎? 非常感謝!
這是一種表達所需邏輯的簡單方法:
select a__contact,
avg(case when a__type = 'missed' then 100.0 else 0 end) as percentage_missed_calls
from table
group by 1;
您的版本失敗,因為您正在分子中使用count()
。 你真的打算sum()
。 count()
計算非NULL
值的數量,並且“ 1”和“ 0”均為非NULL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.