SQL使用count函数计算列的百分比

时间:2017-01-04 10:45:53

标签: sql oracle count

我的数据库中有一个过敏专栏,如果有人没有过敏,那么价值是“不适用”。如果有人确实有过敏症,则会出现过敏症的名称。

我正在尝试使用SQL和COUNT函数来计算过敏的人的百分比!=' N / A'。

虽然我遇到困难,但是任何人都可以指出我正确的方向,或者任何有有用资源的人。

ViewController

4 个答案:

答案 0 :(得分:3)

select sum(case when allergy <> 'N/A' then 1 else 0 end) * 100 / count(*)
from your_table

答案 1 :(得分:2)

这将给出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

答案 2 :(得分:2)

我认为最简单的方法是将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;

答案 3 :(得分:1)

有多种方法可以做到这一点。由于我的朋友已经在几个答案中查询过,复制并粘贴答案正确/合乎道德。因此,使用更加简洁或更简单的查询。请在下面找到查询。

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));
相关问题