簡體   English   中英

SQL使用計數功能計算列的百分比

[英]SQL Calculating a percentage of a column using count function

我的數據庫中有一個過敏專欄,如果某人沒有過敏,則值為“ N / A”;如果某人確實有過敏,則顯示過敏的名稱。

我正在嘗試使用SQL和COUNT函數來計算過敏!='N / A'的人數百分比。

盡管我陷入困境,但是任何人都可以向我指出正確的方向,或者任何有有用資源的人。

Customer | Allergy
--------------------
   A     | Nut allergy
   B     | N/A
   C     | N/A
select sum(case when allergy <> 'N/A' then 1 else 0 end) * 100 / count(*)
from your_table

這將為allergy列提供非N/A值的人所占的百分比(並將忽略對allergy具有[ NULL ]值未知的人):

SELECT 100 * COUNT( DECODE( allergy, 'N/A', NULL, allergy ) )
           / COUNT( allergy )
           AS percentage_with_allergy
FROM   table_name

要將NULL值包含為N/A則:

SELECT 100 * COUNT( DECODE( allergy, 'N/A', NULL, allergy ) )
           / COUNT( 1 )
           AS percentage_with_allergy
FROM   table_name

我認為最簡單的方法是將avg()與條件聚合一起使用:

select avg(case when allergy <> 'N/A' then 100.0 else 0 end)
from t;

如果allergy可能為NULL ,則上述方法會將其視為“ N / A”。 如果您真的只想計算非N / A值:

select avg(case when allergy = 'N/A' then 0.0 else 100.0 end)
from t;

有多種方法可以做到這一點。 由於我的朋友已經詢問了幾個答案,因此復制並粘貼他們的答案是不正確/不道德的 因此,使用更常規的或更簡單的查詢。 請在下面找到查詢。

select (A_SUM/(select count(1) from al_table))*100 as percent from (
select count(1) A_sum from al_table where (allergy <>'N/A' or allergy is not null));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM