BEGIN; with p AS ( SELECT part ,bill_cust ,ship_cust ,round(fb_val_loc/fb_qty,10) AS price ,orderdate ,row_number() OVER (PARTITION BY part,bill_cust, ship_cust ORDER BY orderdate DESC) rn FROM rlarp.osm WHERE fs_line = '41010' AND calc_status <> 'CANCELED' AND COALESCE(part,'') <> '' AND fb_qty <> 0 AND orderdate IS NOT NULL ORDER BY part ,bill_cust ,ship_cust ,orderdate ) --SELECT * FROM p WHERE rn = 1 ,incr AS ( SELECT b.plnt ,b."ddord#" ,b."dditm#" ,b."fgbol#" ,b."fgent#" ,b."diinv#" ,b."dilin#" ,b.promo ,b.return_reas ,b.terms ,b.custpo ,b.dhincr ,b.diext ,b.ditdis ,b.dcodat ,b.ddqdat ,b.dcmdat ,b.dhidat ,b.fspr ,b.remit_to ,b.bill_class ,b.bill_cust ,b.bill_rep ,b.bill_terr ,b.ship_class ,b.ship_cust ,b.ship_rep ,b.ship_terr ,b.quota_rep ,b.account ,b.shipgrp ,b.geo ,b.chan ,b.orig_ctry ,b.orig_prov ,b.orig_post ,b.dest_ctry ,b.dest_prov ,b.dest_post ,b.part ,b.ord_gldc ,b.majg ,b.ming ,b.majs ,b.mins ,b.gldc ,b.glec ,b.harm ,b.clss ,b.brand ,b.assc ,b.fs_line ,b.r_currency ,b.r_rate ,b.c_currency ,b.c_rate ,b.ddqtoi ,b.ddqtsi ,b.fgqshp ,b.diqtsh ,0 fb_qty ,0 fb_cst_loc ,0 fb_cst_loc_cur ,0 fb_cst_loc_fut ,b.fb_qty * p.price - b.fb_val_loc fb_val_loc ,0 fb_val_loc_pl ,b.calc_status ,b.flag ,b.orderdate ,b.requestdate ,b.shipdate ,b.adj_orderdate ,b.adj_requestdate ,b.adj_shipdate ,b."version" ,'last price paid' iter FROM rlarp.osmfs b INNER JOIN p ON p.part = b.part AND p.bill_cust = b.bill_cust AND p.ship_cust = b.ship_cust AND p.rn = 1 WHERE b.orderdate BETWEEN '2019-03-25' AND '2019-05-31' OR b.orderdate BETWEEN '2020-03-25' AND '2020-05-31' ) , ins AS ( INSERT INTO rlarp.osmfs SELECT * FROM incr RETURNING * ) SELECT fspr, sum(fb_val_loc *r_rate) FROM ins GROUP BY fspr; COMMIT;