5 SQL摘要
1、向result_table记录分vendor_name的记录总数
sql := 'insert into '||result_table||' (时间,vendor_name,记录总数)
select 时间,厂家名称,count(*) from '|| check_table || ' where 时间=' || '''' || time || '''' || ' group by 时间,厂家名称 ';
EXECUTE sql;
2、提取check_table表的所有字段名,存入tmp_check_col
sql := 'create temp table tmp_check_col as SELECT a.attname
FROM pg_class as c,pg_attribute as a
where c.relname = '''||check_table||''' and a.attrelid = c.oid and a.attnum>0
and a.attname not in ( ' ||''''||'时间'||''''||' ) ';
EXECUTE sql;
3、打开游标
open datcheck_C FOR
SELECT attname from tmp_check_col ;
4、读取游标,并循环逐个读出字段名
FETCH datcheck_C INTO colname ;
while (colname.attname is not null) loop
5、循环体内,计算为空记录数 [num] 除以 步骤1中的记录总,得到 某字段的缺失率,并更新到对应的单元格内
sql := 'update '||result_table||' b set '||colname.attname||'=(SELECT round(a.num::numeric/b.记录总数::numeric,4) FROM
(
select 时间,厂家名称,count(*) as num from '||check_table||' where '||colname.attname||' is not null and 时间 ='''||time||''' group by 时间, 厂家名称
) a
WHERE a.时间=b.时间 and a.厂家名称=b.vendor_name) where 时间='''||time||'''';
EXECUTE sql;
sql := 'update '||result_table||' set '||colname.attname||' =0 where 时间='''||time||''' and '||colname.attname||' is null';
EXECUTE sql;
FETCH datcheck_C INTO colname;
END loop;
1、提取check_table表的所有字段名,存入tmp_check_col
sql := 'create temp table tmp_check_col as SELECT a.attname
FROM pg_class as c,pg_attribute as a
where c.relname = '''||check_table||''' and a.attrelid = c.oid and a.attnum>0
and a.attname not in ( ''时间'' ) ';
EXECUTE sql;
2、打开游标
open datcheck_C FOR
SELECT attname from tmp_check_col
3、读取游标,逐个读出字段名
FETCH datcheck_C INTO colname ;
while (colname.attname is not null) loop
4、循环体内,向result_table插入某字段为空的记录
sql :='insert into '||result_table||' select * from '||check_table||' where '||colname.attname||' is null and 时间 ='''||time||'''';
EXECUTE sql;
5、循环体内,向check_table删除某字段为空的记录
sql :='delete from '||check_table||' b where '||colname.attname||' is null and 时间 ='''||time||'''';
EXECUTE sql;
FETCH datcheck_C INTO colname;
END loop;
CLOSE datcheck_C;
![](http://dl2.iteye.com/upload/attachment/0102/6680/c365ff12-edee-33b7-9e98-4e41c0c59670.jpg)
![](http://dl2.iteye.com/upload/attachment/0102/6682/0e7ad802-1831-3c62-a659-79937a1ae9c0.jpg)
![](http://dl2.iteye.com/upload/attachment/0102/6684/69fdf69d-7901-3159-86e6-c77e448b41c3.jpg)
![](http://dl2.iteye.com/upload/attachment/0102/6686/611d0167-8a96-3348-8dcb-b4f1db7f1309.jpg)
![](http://dl2.iteye.com/upload/attachment/0102/6688/82da2d60-f291-3f49-a608-50bffff4a55f.jpg)
![](http://dl2.iteye.com/upload/attachment/0102/6690/f283231b-84d9-334e-b6ce-79e3aa6b6443.jpg)
![](http://dl2.iteye.com/upload/attachment/0102/6692/51c238b9-8459-3a20-ac67-4bae3b8c32b4.jpg)
![](http://dl2.iteye.com/upload/attachment/0102/6694/5deac01c-4dbd-3c72-a509-84badb72345f.jpg)
![](http://dl2.iteye.com/upload/attachment/0102/6696/dcc805b2-4756-3ef3-8533-8a7716067b18.jpg)
![](http://dl2.iteye.com/upload/attachment/0102/6698/bdf182ac-17f4-3f29-9365-3f6c5975c4b7.jpg)