函数名wx_qf_hdb(统计日期, 01508); 格式: wx_qf_hdb(20150901, 201508);
功能:提取目前欠费帐龄截止统计日期的各支局欠费回收总数
*/
--start
CREATE FUNCTION wx_qf_hdb(day_id numeric,acct_month numeric) RETURNS TEXT AS $$
DECLARE
LS_SQL VARCHAR(5000);
today VARCHAR(8);
qf_month VARCHAR(6);
month_l INTEGER;
num numeric;
BEGIN
today := TRIM(to_char(day_id,99999999));--截止日期转为字符串
qf_month := TRIM(to_char(acct_month,999999));--欠费月份转为字符串
num := to_number(substr(today,1,6),999999);--区字符串的前6位
month_l := to_date(to_char(day_id+1, ‘9999-99-99‘ ), ‘yyyy-mm-dd‘ )-to_date(to_char(num, ‘9999-99‘ )|| ‘-01‘ , ‘yyyy-mm-dd‘ );--计算当月天数
FOR i IN 1..month_l LOOP
LS_SQL := ‘create table temp_wuxi_qf‘ ||i|| ‘ as
SELECT DISTINCT
A.DAY_ID 统计日期
,A.CHANNEL_NAME 支局名称
,A.OWE_MONTH 欠费账期
,SUM(B.current_charge) 日回收
FROM 表1A LEFT JOIN 表2 B ON A.SERV_ID=B.SERV_ID
WHERE A.AREA_ID=27 AND B.mkt_area_ID=27 AND A.DAY_ID=‘ ||to_char(day_id-month_l+i,99999999)|| ‘ AND A.OWE_MONTH =‘ ||qf_month|| ‘ AND B.ACCT_MONTH=‘ ||qf_month|| ‘
GROUP BY A.DAY_ID,A.CHANNEL_NAME,A.OWE_MONTH‘ ;
EXECUTE LS_SQL;
END LOOP;
--提取日数据
LS_SQL := ‘create table temp_wuxi_qf‘ ||qf_month|| ‘ as ‘ ;
FOR i IN 1..month_l LOOP
LS_SQL := LS_SQL|| ‘SELECT * FROM temp_wuxi_qf‘ ||i|| ‘ UNION ‘ ;
END LOOP;
LS_SQL := LS_SQL|| ‘SELECT * FROM temp_wuxi_qf‘ ||month_l;
EXECUTE LS_SQL;
--汇总日数据
FOR i IN 1..month_l LOOP
LS_SQL:= ‘DROP TABLE temp_wuxi_qf‘ ||i;
EXECUTE LS_SQL;
END LOOP;
--删除所有临时表
RETURN LS_SQL;
END;
$$ LANGUAGE plpgsql;
--end
select wx_qf_hdb(20150903,201508); --运行函数wx_qf_hdb(统计日期,欠费帐期)
DROP FUNCTION wx_qf_hdb(day_id numeric,acct_month numeric); --删除函数
select * from temp_wuxi_qf欠费帐期;--查询表
drop table temp_wuxi_qf欠费帐期; -- 删除表
|