DECLARE
  V_VRPROD FLOAT;
BEGIN
   FOR C_CALCPROD IN (SELECT
                         PL.CDPROCESSO,
                         SUM(PL.NRCPLXITATIV)as NRCPLXITATIV,
                         SUM(H.HORAS) as HORAS
                      FROM
                         PLANATIVTARE PL,
                         (SELECT
                            CDOPERADOR  ,
                            CDFILIAL    ,
                            NRTAREFA    ,
                            NRPLATIVTARE,
                            ROUND(SUM(DTHFAPATIVTA - DTHIAPATIVTA)*24,2) AS HORAS
                          FROM APROATIVTARE
                          GROUP BY CDOPERADOR, CDFILIAL , NRTAREFA , NRPLATIVTARE)H
                      WHERE
                         (PL.CDFILIAL     = '9999') AND
                         (PL.CDFILIAL     = H.CDFILIAL         ) AND
                         (PL.NRTAREFA     = H.NRTAREFA         ) AND
                         (PL.NRPLATIVTARE = H.NRPLATIVTARE     ) AND
                         (PL.CDOPERRESP   = H.CDOPERADOR       ) AND
                         (PL.NRCPLXITATIV > 0)                   AND
                         (PL.IDSITATIVTAR = 'C')                 AND
                         (TO_DATE(PL.DTCONATIVTAR) BETWEEN TO_DATE(ADD_MONTHS(SYSDATE, -2)) AND TO_DATE(SYSDATE))
                      GROUP BY
                         PL.CDPROCESSO
                      ORDER BY PL.CDPROCESSO) LOOP

      IF C_CALCPROD.HORAS = 0 THEN
         V_VRPROD := 0;
      ELSE
         V_VRPROD := C_CALCPROD.NRCPLXITATIV/C_CALCPROD.HORAS;
      END IF;

      UPDATE PROCESSO
      SET VRPRODMEDES = V_VRPROD
      WHERE CDPROCESSO = C_CALCPROD.CDPROCESSO;
   END LOOP;
END;
/
COMMIT;
/
