2017-05-05 12 views

答えて

1

あなたはPostgresのを使用していると仮定すると:

CREATE FUNCTION count_null (row my_table) 
    RETURNS INTEGER 
AS $$ 
    return len([x for x in row if x is None]) 
$$ LANGUAGE plpythonu; 

しかし、私は好きでそれを呼び出す場合には、引数の型と一致していません= 9.3の場合、json変換を使用してこれを行うことができます。

create or replace function count_null(
    _r json 
) returns integer as $$ 
    select 
     count(1)::integer 
    from 
     (
      select 
       row_to_json(json_each(_r)) as condensed_record 
     ) as __base 
    where 
     condensed_record->>'value' is null; 
$$ language sql immutable; 

--------- 

select 
    count_null(row_to_json(my_table)) 
from 
    my_table; 

これにはlangua plpythonuではなくSQLを使用するので、クエリプランナはある程度最適化できます。

関連する問題