Gracias por sus respuestas, hasta ahora el script va así:

select  tr.cedula,'nombre_prueba' as nombre,hq.mes mes_nomina , serie.mes
mes_serie,
(select min(fecha_ingreso) from personal a,trabajador b where
b.cedula=tr.cedula) as fch_ingreso,
(COALESCE((SELECT max(fecha_egreso) from trabajador where
cedula=tr.cedula), now()::date)) as fch_egreso,
(COALESCE((SELECT max(extract(year from fecha_egreso)) from trabajador
where cedula=tr.cedula),extract(year from now())))::integer as fch_tope,
sum(case hq.anio when (
                        (COALESCE((SELECT max(extract(year from
fecha_egreso)) from trabajador where cedula=tr.cedula),extract(year from
now())))-5)
        then hq.monto_asigna else 0 end) as anio6,
sum(case hq.anio when ((COALESCE((SELECT max(extract(year from
fecha_egreso)) from trabajador where cedula=tr.cedula),extract(year from
now())))-4) then hq.monto_asigna else 0 end) as anio5,
sum(case hq.anio when ((COALESCE((SELECT max(extract(year from
fecha_egreso)) from trabajador where cedula=tr.cedula),extract(year from
now())))-3) then hq.monto_asigna else 0 end) as anio4,
sum(case hq.anio when ((COALESCE((SELECT max(extract(year from
fecha_egreso)) from trabajador where cedula=tr.cedula),extract(year from
now())))-2) then hq.monto_asigna else 0 end) as anio3,
sum(case hq.anio when ((COALESCE((SELECT max(extract(year from
fecha_egreso)) from trabajador where cedula=tr.cedula),extract(year from
now())))-1) then hq.monto_asigna else 0 end) as anio2,
sum(case hq.anio when (COALESCE((SELECT max(extract(year from
fecha_egreso)) from trabajador where cedula=tr.cedula),extract(year from
now()))) then hq.monto_asigna else 0 end) as anio1
from (SELECT generate_series(1,12) as mes) as serie  right join
historicoquincena hq on serie.mes=hq.mes,
conceptotipopersonal ctp, trabajador tr,conceptofijo cf,concepto
cp,personal per
where tr.id_trabajador = hq.id_trabajador and
tr.cedula = per.cedula and
hq.id_concepto_tipo_personal=ctp.id_concepto_tipo_personal and
ctp.id_concepto_tipo_personal=cf.id_concepto_tipo_personal and
ctp.id_concepto=cp.id_concepto and
cf.id_trabajador=tr.id_trabajador and
tr.cedula = xxxxxxx
group by 1,2,3,4,5
order by 3,4

Y el resultado así:


cedula nombre mes_nomina mes_serie fch_ingreso fch_egreso fch_tope anio6
anio5 anio4 anio3 anio2 anio1
xxxxxxx nombre_prueba 1 1 2017-08-28 2018-02-09 2018 0 0 0 0 0 1282238.2
xxxxxxx nombre_prueba 2 2 2017-08-28 2018-02-09 2018 0 0 0 0 0 641119.1
xxxxxxx nombre_prueba 9 9 2017-08-28 2018-02-09 2018 0 0 0 0 839236.86 0
xxxxxxx nombre_prueba 10 10 2017-08-28 2018-02-09 2018 0 0 0 0 963316.33 0
xxxxxxx nombre_prueba 11 11 2017-08-28 2018-02-09 2018 0 0 0 0 1173247.17 0
xxxxxxx nombre_prueba 12 12 2017-08-28 2018-02-09 2018 0 0 0 0 2807244 0

Supongo se puede optimizar pero resoveré antes con sus sugerencias, muchas
gracias. Estaré comentando la solución.

Feliz día!

Reply via email to