buneo lo mejor que puedo hacer con solo SQL es esto:

(select null::date as fecha,sum(tipo1), sum(tipo2), sum(tipo1+(tipo2*-1)), 'Resumen'::text

  from (select id, fecha, imp as tipo1, 0 as tipo2, imp

          from foo

         where tipo= 1

         union

        select id, fecha, 0 as tipo1, imp as tipo2, imp*-1

          from foo

         where tipo= 2) as Aux

          where  fecha <=   '2012-04-01'  )
          union all


(select fecha,tipo1, tipo2, sum(imp) over (order by id), 'Detalle'::text

  from (select id, fecha, imp as tipo1, 0 as tipo2, imp

          from foo

         where tipo= 1

         union

        select id, fecha, 0 as tipo1, imp as tipo2, imp*-1

          from foo

         where tipo= 2) Aux

          where  fecha between    '2012-04-01' and '2012-04-30')
          union all

(select null::date as fecha,sum(tipo1), sum(tipo2), sum(tipo1+(tipo2*-1)), 'Resumen'::text

  from (select id, fecha, imp as tipo1, 0 as tipo2, imp

          from foo

         where tipo= 1

         union

        select id, fecha, 0 as tipo1, imp as tipo2, imp*-1

          from foo

         where tipo= 2) as Aux

          where  fecha >=   '2012-04-30'  order by fecha desc limit 1)

si entiendo bien lo que me pides tendrás que hacerlo con una función en plpgsql usando cursores.
saludos
<http://www.uci.cu/>


10mo. ANIVERSARIO DE LA CREACION DE LA UNIVERSIDAD DE LAS CIENCIAS 
INFORMATICAS...
CONECTADOS AL FUTURO, CONECTADOS A LA REVOLUCION

http://www.uci.cu
http://www.facebook.com/universidad.uci
http://www.flickr.com/photos/universidad_uci

Responder a