I want to delete all the rows on a table with a job_id of 214. Then I want to insert other records back into job_id 214. I think the delete is deleting the rows that I just got done inserting. I thought this would work from [this][1], the last answer. When I comment out line 1, un-comment line 2 and comment the 2nd to last row, the one with the insert, I get the data output I am looking for. I just need it to insert that data output, but it does not seem to be inserting or else is being deleted right away.
WITH cte_delete AS(DELETE FROM fdw_ca_millingdb.job_detail WHERE job_id = 214),
--WITH
newRows AS (
WITH abcT AS
(SELECT fdw_ca_millingdb.item_abc_map.item_id AS item_id, SUM(ordered_quantity) AS ordered_quantity FROM work_order_dadsfetail
LEFT JOIN fdw_ca_millingdb.item_abc_map ON fdw_ca_millingdb.item_abc_map.abc_item_id = work_order_detail.item_id
WHERE work_order_detail.item_id ILIKE ANY (array['1%', '2%', '3%', '4%']) AND work_order_detail.id = 254919
GROUP BY fdw_ca_millingdb.item_abc_map.item_id),
logT AS
(SELECT fdw_ca_millingdb.batcher_log.item_id batcher_log_item_id, SUM(fdw_ca_millingdb.batcher_log.ending_weight - fdw_ca_millingdb.batcher_log.starting_weight) AS actual_weight FROM fdw_ca_millingdb.job
LEFT JOIN fdw_ca_millingdb.batcher_log ON fdw_ca_millingdb.batcher_log.job_id = fdw_ca_millingdb.job.id
WHERE fdw_ca_millingdb.job.work_order_id = 254919
GROUP BY fdw_ca_millingdb.batcher_log.item_id)
SELECT 214 AS job_id, ROW_NUMBER() OVER(ORDER BY abcT.item_id) - 1 AS line_num, ordered_quantity - actual_weight AS ordered_quantity,
abcT.item_id AS item_id, fdw_ca_millingdb.item.description AS item_description, bin.id AS bin_id FROM abcT
FULL JOIN logT ON logT.batcher_log_item_id = abcT.item_id
LEFT JOIN fdw_ca_millingdb.item ON fdw_ca_millingdb.item.id = abcT.item_id
LEFT JOIN fdw_ca_millingdb.bin ON fdw_ca_millingdb.bin.item_id = abcT.item_id WHERE bin.mode = 1)
INSERT INTO fdw_ca_millingdb.job_detail (job_id, line_num, ordered_quantity, item_id, item_description, bin_id)
SELECT job_id, line_num, ordered_quantity, item_id, item_description, bin_id FROM newRows```
[1]: https://dba.stackexchange.com/questions/267243/want-to-delete-then-insert-with-single-statement-using-a-cte-in-postgres