CREATE OR REPLACE function getzaikolocation(kijunbi date, phinmokucd text, plotno text) returns table ( 
     hinmokucd text
    , lotno text
    , sokocd text
    , locationcd text
    , suryo numeric
    , tanicd text
    , zaikotanka numeric
    , zaikokingaku numeric
) AS $$ 
select distinct
z.hinmokucd
,z.lotno
,z.sokocd
,z.locationcd
,first_value(z.suryo) over (partition by z.hinmokucd, z.lotno, z.locationcd, z.sokocd order by z.denpyobi desc, z.denpyono desc) as suryo
,z.tanicd
,first_value(z.zaikotanka) over (partition by z.hinmokucd, z.lotno, z.locationcd, z.sokocd order by z.denpyobi desc, z.denpyono desc) as zaikotanka
,first_value(z.zaikokingaku) over (partition by z.hinmokucd, z.lotno, z.locationcd, z.sokocd order by z.denpyobi desc, z.denpyono desc) as zaikokingaku
from getzaikomotocho(clock_timestamp()::date, phinmokucd) z
     $$ LANGUAGE sql;
