1

I'm not finding the error. I need to update a table based on the lowest date for each item by removing duplicates.

FOR temprow IN
   SELECT MIN(orcitem_dtime_inclusao), orcitem_orc_id FROM orcamento_itens GROUP BY orcitem_orc_id ORDER BY orcitem_orc_id ASC
LOOP
  UPDATE orcamentos SET orc_dtime_orcamento = temprow.orcitem_dtime_inclusao WHERE orc_id = temprow.orcitem_orc_id;
END LOOP;
2
  • "I'm not finding the error." what error? Does it throw an error? Does it not update the table? Or ain't the update correct? OR something else? What's the problem? Commented May 29, 2021 at 1:23
  • Please provide sample data and desired results. Commented May 29, 2021 at 1:27

1 Answer 1

2

You seem to want:

UPDATE orcamentos o
    SET orc_dtime_orcamento = oi.min_orcitem_dtime_inclusao
    FROM (SELECT orcitem_orc_id,
                 MIN(orcitem_dtime_inclusao) as min_orcitem_dtime_inclusao
          FROM orcamento_itens
          GROUP BY orcitem_orc_id
         ) oi
    WHERE oi.orcitem_orc_id = o.orc_id;

You don't need a cursor or other looping mechanism. You can do this all in a single query.

Sign up to request clarification or add additional context in comments.

1 Comment

Woww. Perfect. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.