--EXPLAIN (analyze)
select  
        	rd.evn_id,rd.evn_rid,rd.lpusection_id--,_validation_code[14],_validation_title[14]
        from r12.registrydata rd 
				join r12.registryusluga ru on ru.registry_id=rd.registry_id and ru.evn_id=rd.evn_id 
				join r12.marikmu mk on ru.registryusluga_codeusl=mk.marikmu_code and mk.marikmu_pos>0
				left join v_MedStaffFact MedStaffFact on ru.MedStaffFact_id = MedStaffFact.MedStaffFact_id
				left join MedSpecOms on MedSpecOms.MedSpecOms_id = MedStaffFact.MedSpecOms_id
        where
        	rd.registry_id = 14869 
            and (rd.region_data ->> 'item_type' = 'disp'
								or rd.region_data ->> 'evnclass_sysnick'= 'EvnVizitPL')
						and not exists(select 1 from r12.registryusluga ru2 where ru2.registry_id=rd.registry_id and ru2.evn_id=rd.evn_id
														and (ru2.registryusluga_codeusl in ('002075','102075') or left(ru2.registryusluga_codeusl,3) in ('061','161')))
						--исключение оказанных ранее услуг  по INC000014547284 
						and not exists (select 1 from v_evnuslugadispdop evnusldd 
														join dbo.dopdispinfoconsent ddi on evnusldd.dopdispinfoconsent_id=ddi.dopdispinfoconsent_id
														where evnusldd.evnuslugadispdop_id=ru.evnusluga_id and ddi.dopdispinfoconsent_isearlier=2)
						and exists(select 1 from v_evnusluga usl
																--from (select * from v_evnusluga usl where usl.person_id=rd.person_id ) usl
																left join v_MedStaffFact MedStaff on usl.MedStaffFact_id = MedStaff.MedStaffFact_id
																left join MedSpecOms ms on ms.MedSpecOms_id = MedStaff.MedSpecOms_id
												where usl.evnusluga_id<>ru.evnusluga_id and usl.uslugacomplex_id=ru.uslugacomplex_id and usl.person_id=rd.person_id 
												and usl.lpu_id=2222030 and usl.paytype_id=120101000000023 and ms.MedSpecClass_id=MedSpecOms.MedSpecClass_id 
												and usl.evnusluga_setdt=ru.registryusluga_setdate)
