drop view if exists IES.V_OMS_SCHET_ZAP;

ALTER TABLE IES.T_SCHET_SLUCH ALTER COLUMN "lpu_1" SET DATA TYPE varchar(17);

ALTER TABLE IES.T_SCHET_SLUCH ALTER COLUMN "lpu_1" DROP NOT NULL;

create view IES.V_OMS_SCHET_ZAP as
select sz.SchetZapID, schet.schetID as MtrSchetOut
from ies.T_SCHET_ZAP sz
    join ies.T_SCHET s on (sz.schet = s.schetid)
    left join lateral (select * from ies.T_SCHET_SLUCH ss where ss.schetzap = sz.schetzapid limit 1) aa on true
    left join lateral (
        select sout.* 
        from ies.T_SCHET_SLUCH ssOut 
            join ies.T_SCHET_ZAP szOut on (ssOut.schetzap = szOut.schetzapid and szOut.IsDelete = false) 
            join ies.T_SCHET sOut on (szOut.schet = sOut.schetid and sOut.isdelete = false and sOut.schetkind = 0 and sOut.C_OKATO1 <> sOut.OKATO_OMS)
        where (ssOut.omsschetsluch = aa.schetsluchid and ssOut.isdelete = false) limit 1) schet on true
where s.isdelete = false;
