begin; WITH d AS ( DELETE FROM rlarp.osm_pool WHERE logid IN ( SELECT p.logid --jsonb_agg(DISTINCT p.quota_rep_descr), --l.doc->>'user' usr, --l.doc->>'message' com, --(l.doc->>'stamp')::timestamp stamp, ,sum(value_usd) value_usd FROM rlarp.osm_pool p INNER JOIN rlarp.osm_log l ON l.id = p.logid WHERE l.doc->>'user' = 'Baggetta, Antony' AND dsm NOT IN ('10023','10026','10032','30010','30033','30035','90050') --quota_rep_descr IN ('JORDAN BUKOWSKI' ,'RICHARD MEULE') AND logid > 1 GROUP BY p.logid --p.quota_rep_descr, --l.doc->>'user', --l.doc->>'message', --(l.doc->>'stamp')::timestamp ) AND dsm NOT IN ('10023','10026','10032','30010','30033','30035','90050') ) SELECT * FROM d