如何计算SQL中的个案数?

时间:2016-10-08 08:09:22

标签: sql postgresql case conditional-statements

如何在SQL中查找案例数?例如,以下代码有5个Case语句

Select
up.user_id,
(
    case when up.email is null then 0 else 1 end
    +
    case when up.bio is null then 0 else 1 end
    +
    case when up.website is null then 0 else 1 end
    +
    case when up.location is null then 0 else 1 end
    +
    case when up.name is null then 0 else 1 end
) * 100 / **5** as complete
from users_profiles up

我正在使用PostgreSQL

1 个答案:

答案 0 :(得分:4)

使用具有可变数量参数的函数,例如:

create or replace function not_null_ratio(variadic args text[])
returns numeric language plpgsql as $$
declare
    res numeric = 0;
begin
    for i in 1..array_length(args, 1) 
    loop
        res := res+ (args[i] is not null)::integer;
    end loop;
    return res * 100 / array_length(args, 1);
end $$;

select not_null_ratio('a', 'b', null, 'd');

   not_null_ratio    
---------------------
 75.0000000000000000
(1 row)

在您的查询中:

select
    up.user_id,
    not_null_ratio(up.email, up.bio, up.website, up.location, up.name) as complete
from users_profiles up

SQL函数也可以包含可变数量的参数。这种变体可能会快一点:

create or replace function not_null_ratio_sql(variadic args text[])
returns numeric language sql as $$
    select count(elem) * 100.0 / count(*)
    from unnest(args) elem
$$;

select not_null_ratio_sql('a', 'b', null);

 not_null_ratio_sql  
---------------------
 66.6666666666666667
(1 row)