select e.Evn_id,veup1.UslugaComplex_Code1 as UslugaComplex_Code,veup1.UslugaComplex_Name1 as UslugaComplex_Name,veup1.EvnUslugaPar_setDT
	    from v_EvnUslugaPar veup  
		left JOIN v_Evn ve    ON veup.EvnUslugaPar_rid = ve.Evn_id
		 LEFT JOIN LATERAL 
		(select Evn_id from v_Evn  e    where e.Evn_id =veup.EvnUslugaPar_rid 
		and e.EvnClass_id in (3,30)) rid
		 on true 
		 LEFT JOIN LATERAL 
		(select Evn_id,Evn_setDate from v_Evn e  
		where  e.Evn_rid=rid.Evn_id and e.EvnClass_id=47 and e.Evn_id <>veup.EvnUslugaPar_id ) e  on true 
		 LEFT JOIN LATERAL 
		( select nomenmedusluga_uslugacode as UslugaComplex_Code1
    	,nomenmedusluga_name as UslugaComplex_Name1,veup1.EvnUslugaPar_setDT
		from  v_EvnUslugaPar veup1  
		 left join lateral  (select   uc1.nomenmedusluga_uslugacode ,
		 uc1.nomenmedusluga_name 
			   from nsi.p_NomenMedUsluga_getUsluga(veup1.UslugaComplex_id) uc1 where uc1.nomenmedusluga_uslugacode is not null  LIMIT 1 ) 
			   usl  on true 
		where veup1.EvnUslugaPar_id=e.Evn_id and veup1.EvnUslugaPar_setDT < veup.EvnUslugaPar_setDT
		) veup1
		 on true 
		 LEFT JOIN LATERAL  ( select COALESCE(nmu.NomenMedUsluga_UslugaCode, nmu2011.NomenMedUsluga_UslugaCode, nmu2004.NomenMedUsluga_UslugaCode) as UslugaComplex_Code
    	,COALESCE(nmu.NomenMedUsluga_Name, nmu2011.NomenMedUsluga_Name, nmu2004.NomenMedUsluga_Name) as UslugaComplex_Name
		from   dbo.v_UslugaComplex vuc   
    	LEFT join nsi.NomenMedUsluga nmu   ON nmu.NomenMedUsluga_UslugaCode = vuc.UslugaComplex_Code
    	LEFT JOIN dbo.v_UslugaComplex vuc2011    ON vuc2011.UslugaComplex_id = vuc.UslugaComplex_2011id
    	LEFT join nsi.NomenMedUsluga nmu2011   ON nmu2011.NomenMedUsluga_UslugaCode = vuc2011.UslugaComplex_Code
    	LEFT JOIN dbo.v_UslugaComplex vuc2004    ON vuc2004.UslugaComplex_id = vuc.UslugaComplex_2004id
    	LEFT join nsi.NomenMedUsluga nmu2004   ON nmu2004.NomenMedUsluga_UslugaCode = vuc2004.UslugaComplex_Code
		where   vuc.UslugaComplex_id = veup.UslugaComplex_id) veup2  on true 
		where substring(veup2.UslugaComplex_Code,1,10)=substring(veup1.UslugaComplex_Code1,1,10)
		and  veup.EvnUslugaPar_id=$1
