DECLARE 
   V_COUNT NUMBER;
BEGIN
   SELECT 
      COUNT(*)
   INTO 
      V_COUNT
   FROM 
      POSESTCONS;

   IF V_COUNT = 0 THEN
      INSERT INTO 
         POSESTCONS
            (CDFILIAL, 
             CDPRODUTO, 
             DTPOSESTCON, 
             QTESTDIACON, 
             VRESTDIACON, 
             VRESTDIACOM1,
             VRESTDIACOM2, 
             VRESTBRUTCON, 
             VRESTBRUTCM1, 
             VRESTBRUTCM2, 
             QTESTANTCON,
             DTCUSTANTCON, 
             VRESTANTCON, 
             VRESTANTCOM1, 
             VRESTANTCOM2, 
             VRBRUTANTCON, 
             VRBRUTANTCM1,
             VRBRUTANTCM2, 
             IDPOSZEROCON)
         (SELECT 
             CDFILIAL, 
             CDPRODUTO, 
             DTPOSIESTQ, 
             SUM(QTESTOQDIA), 
             SUM(VRESTOQDIA), 
             SUM(VRESTOQDIAM1),
             SUM(VRESTOQDIAM2), 
             SUM(VRESTOQBRUT), 
             SUM(VRESTOQBRUM1), 
             SUM(VRESTOQBRUM2), 
             SUM(QTESTOQANT),
             MAX(DTCUSTANT), 
             SUM(VRESTOQANT), 
             SUM(VRESTOQANTM1), 
             SUM(VRESTOQANTM2),  
             SUM(VRBRUTOANT), 
             SUM(VRBRUTOANTM1),
             SUM(VRBRUTOANTM2), 
             MAX(IDPOSIZERO)
          FROM 
             POSESTDIA
          GROUP BY 
             CDFILIAL, 
             CDPRODUTO, 
             DTPOSIESTQ);
      COMMIT;
   END IF;
END;
/
