SELECT *
FROM

(

           select i31.nr01 as nr01,
                  i31.p01  as p01,
                  i31.p02  as p02,
                  i31.p03  as p03,
                  i31.p04  as p04,
                  i31.p015 as p015,
                  i31.p031 as p031,
                  i31.remfdate as remfdate, 
                  i31.remftime as remftime, 
                  sum(if(i01.nr01 is null, 0, i01.p012*(i15.p03-i15.p04))) as ypol, 
                  0 as 
           FROM i31
           LEFT JOIN i32 ON i31.p01=i32.p01
                         && i31.p02=i32.p02
                         && i32.p010=1
           LEFT JOIN i01 ON i01.nr01=i32.p00
                         && i32.p010=1
           LEFT JOIN i15 ON i15.p01=i01.p05

           WHERE i31.p01='{pse_cod}' && i01.nr01 IS NOT NULL
           GROUP BY i31.p01, i31.p02
) as t1
WHERE ypol>0
ORDER BY p03, remfdate, remftime, nr01
LIMIT {alltrim(str(peg_nnn,10))} ;