if exists(select 1 from sys.views V inner join sys.[schemas] S on  v.schema_id = s.schema_id where s.name='IES' and v.name = 'V_OMS_SCHET_ZAP' and v.type = 'v')
drop view IES.V_OMS_SCHET_ZAP
GO
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)
outer apply(select top 1 * from ies.T_SCHET_SLUCH ss where ss.schetzap = sz.schetzapid) aa
outer apply(select top 1 sout.* 
			from ies.T_SCHET_SLUCH ssOut 
			join ies.T_SCHET_ZAP szOut on (ssOut.schetzap = szOut.schetzapid and szOut.IsDelete = 0) 
			join ies.T_SCHET sOut on (szOut.schet = sOut.schetid and sOut.isdelete = 0 and sOut.schetkind = 0 and sOut.C_OKATO1 <> sOut.OKATO_OMS)
			 where (ssOut.omsschetsluch = aa.schetsluchid and ssOut.isdelete = 0)) schet
where s.isdelete = 0