postgresql 统计一张表每个字段不为NULL和空值的数量

创建一张表:

create table test_table(
    year int,
    m01 int,
    m02 int,
    m03 int,
    m04 int
);
insert into test_table values(2018, 1,2,3,4);
insert into test_table values(2019, 10,20,30,null);
insert into test_table values(2020, 100,200,null,'');

表数据:

yearm01m02m03m04
20181234
2019102030null
2020100200null

创建一个函数,SQL代码:

CREATE OR REPLACE FUNCTION "public"."get_film"("database1" varchar, "table1" varchar)
  RETURNS TABLE("database" text, "table" text, "column" text, "sum" int8, "ratio" text) AS $BODY$
declare
v_msg character varying :='';
v_msg1 character varying :='';
course refcursor;
BEGIN
if not exists(select 1 from information_schema.columns
where table_schema=''||database1||'' and table_name=''||table1||'')
then
RAISE EXCEPTION '请输入正确的库名和表名!';
end if;
open course for execute 'select column_name
from information_schema.columns
where table_schema='''||database1||''' and table_name='''||table1||'''
order by ordinal_position;';
loop
fetch course into v_msg1;
if found then
v_msg :=v_msg||'select '''||database1||''' as database1,'''||table1||''' as table1,'''||v_msg1||''' as column1,
sum(case when '||v_msg1||' is null or '||v_msg1||'::varchar ='''' then 0 else 1 end) as sum1,
round(sum(case when '||v_msg1||' is null or '||v_msg1||'::varchar ='''' then 0 else 1 end)/count(*)::numeric*100,2)||''%'' as ratio1
from '||database1||'.'||table1||' group by 1
union all'||chr(10);
        else
            exit;
        end if;
end loop;
close course;
v_msg :=v_msg||'select '''||database1||''' as database1,'''||table1||''' as table1,''count_sum'' as column1,
count(*) as sum1,''100.00%'' as ratio1
from '||database1||'.'||table1||' group by 1';
return query execute v_msg;
END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000

调用:

select * from public.get_film('public','test_table')

查询结果:

databasetablecolumnsumratio
publictest_tableyear3100.00%
publictest_tablem013100.00%
publictest_tablem023100.00%
publictest_tablem03266.67%
publictest_tablem04133.33%
publictest_tablecount_sum3100.00%
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值