我有一张存储付款的表格。我需要合并付款日期和付款日期。
所以我会有类似的东西:
DeudaId Date Value
1 2016-01-01 $100 <- This come from a table
1 2016-01-02 $0 <- This was calculated
1 2016-01-03 $0 <- This was calculated
1 2016-01-04 $100 <- This come from a table
我有这个必要的解决方案,但对我的情况来说太慢了:
CREATE OR REPLACE FUNCTION build_dates2()
RETURNS TABLE (id INTEGER, cobrador_id INTEGER, fecha DATE)
LANGUAGE plpgsql
IMMUTABLE STRICT
AS $function$DECLARE min_date DATE;
DECLARE
r RECORD;
fecha RECORD;
BEGIN
for r in (SELECT * FROM recaudo_deuda) LOOP
for fecha in (select toFecha(r.fecha) + s.a AS dates from generate_series(0, r.plazo) as s(a)) LOOP
return query VALUES ( r.id, r.cobrador_id, fecha.dates);
END LOOP;
END LOOP;
END
$function$;
SELECT * from build_dates2()
我知道我可以创建另一个表并使用触发器存储数据。我想知道是否存在一种有效的方法来即时执行此操作。
我还尝试使用 recaudo_deuda 表的最小值/最大值生成日期列表,但是我看不到如何从中构建结果:
CREATE OR REPLACE FUNCTION public.build_dates()
RETURNS TABLE(dates date)
LANGUAGE plpgsql
IMMUTABLE STRICT
AS $function$
DECLARE min_date DATE;
DECLARE dias INTEGER;
BEGIN
SELECT min(fecha), extract(DAY from max(fecha) - min(fecha))
from recaudo_deuda INTO min_date, dias;
RETURN QUERY select min_date + s.a AS dates from generate_series(0,dias) as s(a);
END
$function$