SELECT
    0        as type,
    d86nr01  as d86nr01,
    d25nr01  as d25nr01,
    d00nr01  as d00nr01,
    d00p19  as d00p19,
    d29p03  as d29p03,
    d29p02  as d29p02,
    sum(papel) as papel,
    sum(tipel) as tipel,
    sum(papro) as papro,
    sum(tipro) as tipro

FROM

( /* t1 = erga + paragelies - parastatika */

/*paraggelies - timologia pelaton */

select
    d25.p101 as d86nr01,
    d25.nr01 as d25nr01,
    d25.p03  as d00nr01,
    d00.p19  as d00p19,
    d29.p03  as d29p03,
    d29.p02  as d29p02,
    sum(if(a57.p0109 IS NULL, 0, a57.p0109)) as papel,
    sum(if(t01.p03 IS NULL, 0, t01.p03)) as tipel,
    0 as papro,
    0 as tipro

FROM d25
LEFT JOIN d29 ON d29.p01=d25.p010
LEFT JOIN d00 ON d00.nr01=d25.p03
LEFT JOIN a57 ON a57.p503=d25.nr01 && a57.p591='0'
LEFT JOIN a55 ON a55.p503=d25.nr01
LEFT JOIN t01 ON t01.p302=a55.nr01 && t01.p303='2'
WHERE  d25.p100='d86'
   &&  d25.p101='{nnr01}'
   &&  d29.p03 IN ({peg_str1})
GROUP BY d25.nr01

UNION ALL

/*paraggelies - timologia promithefton */

select
    d25.p101 as d86nr01,
    d25.nr01 as d25nr01,
    d25.p03  as d00nr01,
    d00.p19  as d00p19,
    d29.p03  as d29p03,
    d29.p02  as d29p02,
    0 as papel,
    0 as tipel,
    sum(if(a67.p0109 IS NULL, 0, a67.p0109)) as papro,
    sum(if(t01.p03 IS NULL, 0, t01.p03)) as tipro

FROM d25
LEFT JOIN d29 ON d29.p01=d25.p010
LEFT JOIN d00 ON d00.nr01=d25.p03
LEFT JOIN a67 ON a67.p503=d25.nr01 && a67.p591='0'
LEFT JOIN a56 ON a56.p503=d25.nr01
LEFT JOIN t01 ON t01.p302=a56.nr01 && t01.p303='1'
WHERE  d25.p100='d86'
   &&  d25.p101='{nnr01}'
   &&  d29.p03 IN ({peg_str1})
GROUP BY d25.nr01

) as t1

GROUP BY d25nr01;
