DELETE FROM tpsv.dcard WHERE app_version = 'app_forecast_name'; WITH baseline AS ( SELECT o.id ,o.logid ,o."Trans. Date" ,o."Post Date" ,o."Description" ,o."Amount" ,o."Category" ,o."Party" ,o."Reason" ,'app_forecast_name' "version" ,'actuals' iter ,null::bigint app_logid FROM tpsv.dcard o WHERE ( --base period orders booked.... "Trans. Date" BETWEEN 'app_baseline_from_date'::date AND 'app_baseline_to_date'::date --...or any open orders currently booked before cutoff.... OR ("Category" IN (app_openstatus_code) and "Trans. Date" <= 'app_openorder_cutoff'::date) --...or anything that shipped in that period OR ("Post Date" BETWEEN 'app_baseline_from_date'::date AND 'app_baseline_to_date'::date) ) --be sure to pre-exclude unwanted items, like canceled orders, non-gross sales, and short-ships UNION ALL SELECT o.id ,o.logid ,o."Trans. Date" + interval '1 year' AS "Trans. Date" ,o."Post Date" + interval '1 year' AS "Post Date" ,o."Description" ,o."Amount" ,o."Category" ,o."Party" ,o."Reason" ,'app_forecast_name' "version" ,'plug' iter ,null::bigint app_logid FROM tpsv.dcard o LEFT OUTER JOIN fc.perd tdate ON (o."Trans. Date" + interval '1 year' )::date <@ tdate.drange LEFT OUTER JOIN fc.perd pdate ON (o."Post Date" + interval '1 year' )::date <@ pdate.drange WHERE "Trans. Date" BETWEEN 'app_plug_fromdate'::date AND 'app_plug_todate'::date --be sure to pre-exclude unwanted items, like canceled orders, non-gross sales, and short-ships ) ,incr AS ( SELECT o.id ,o.logid ,o."Trans. Date" + interval '1 year' AS "Trans. Date" ,o."Post Date" + interval '1 year' AS "Post Date" ,o."Description" ,o."Amount" ,o."Category" ,o."Party" ,o."Reason" ,'app_forecast_name' "version" ,'baseline' iter ,null::bigint app_logid FROM baseline o LEFT OUTER JOIN fc.perd tdate ON (o."Trans. Date" + interval '1 year' )::date <@ tdate.drange LEFT OUTER JOIN fc.perd pdate ON (o."Post Date" + interval '1 year' )::date <@ pdate.drange ) ,ins AS ( INSERT INTO tpsv.dcard SELECT * FROM incr i WHERE i."Trans. Date" >= 'app_first_forecast_date'::date OR i."Post Date" >= 'app_first_forecast_date'::date RETURNING * ) SELECT COUNT(*) num_rows FROM ins