drop view ei_denik_vw2; create view ei_denik_vw2 as select po.cislo, po.popis, sm.pocet as pocetm, case when sm.pocet>1 then null else dm.ucet end as ucetm, case when sm.pocet>1 then null else dm.anal end as analm, case when sm.pocet>1 then null else om.popis end as popism, case when sd.pocet>1 then null else dm.doklad end as dokladm, sd.pocet as pocetd, case when sd.pocet>1 then null else dd.ucet end as ucetd, case when sd.pocet>1 then null else dd.anal end as anald, case when sm.pocet>1 then null else od.popis end as popisd, case when sd.pocet>1 then null else dd.doklad end as dokladd, case when sm.castka!=sd.castka then 'NaN'::float8 else sm.castka end as castka from ei_popis po left join (select cislo, count(*) as pocet, sum(castka) as castka from ei_denik where mdd='M' group by cislo) as sm using (cislo) left join (select cislo, count(*) as pocet, sum(castka) as castka from ei_denik where mdd='D' group by cislo) as sd using (cislo) left join (select distinct on (cislo) cislo, ucet, anal, doklad from ei_denik where mdd='M') as dm using (cislo) left join (select distinct on (cislo) cislo, ucet, anal, doklad from ei_denik where mdd='D') as dd using (cislo) left join ei_osnova om on (om.ucet=dm.ucet and om.anal=dm.anal) left join ei_osnova od on (od.ucet=dd.ucet and od.anal=dd.anal) ;