SELECT
last_value ( typechange ) OVER w,
pindex,
lid,
last_value ( modified ) OVER w,
last_value ( created ) OVER w,
last_value ( modifiedby ) OVER w,
last_value ( createby ) OVER w,
last_value ( cost ) FILTER ( WHERE cost IS NOT NULL ) OVER w,
last_value ( sell ) FILTER ( WHERE sell IS NOT NULL ) OVER w
FROM ps._delta_ext
WHERE pindex = Ppindex AND
( Plid IS NULL OR lid = Plid ) AND
( Ptimestamp IS NULL OR modified <= Ptimestamp )
GROUP BY lid, pindex
WINDOW w AS ( PARITION BY lid, pindex ORDER BY created );