
			with curDateTime as (select dbo.tzGetDate() as curDate),
			vars as (
				select
					
					'9990010250'::bigint as LpuId
			),
			tab1 as (
				select
					'TimetableStac_' ||  TTS.TimetableStac_id::text as keyNote,
					COALESCE(EvnPS.EvnPS_setDT,TTS.TimetableStac_setDate) as sortDate,
					EST.PrehospStatus_id as groupField,
					null as EvnDirection_id,
					null as EvnDirection_IsAuto,
					null::timestamp as EvnDirection_insDT,
					PLI.PersonLpuInfo_IsAgree as PersonLpuInfo_IsAgree,
					null as EvnDirection_IsConfirmed,
					EvnPS.EvnDirection_Num as EvnDirection_Num,
					EvnPS.EvnDirection_setDT as EvnDirection_setDate,
					coalesce(EvnPS.Diag_did,CCC.Diag_gid) as Diag_did,
					EvnPS.LpuSection_did as LpuSection_did,
					TTSLSd.LpuSection_Name as LpuSection_dName,
					EvnPS.Lpu_did,
					LPUd.Lpu_Name as Lpu_dName,
					EvnPS.Org_did,
					ORGd.Org_Name as Org_dName,
					null as DirType_id,
					null as Direction_exists,
					TTS.TimetableStac_setDate as TimetableStac_setDate,
					case when TTS.TimetableType_id = 6 then
						COALESCE(TTSLS.LpuSectionProfile_Name,'')
						 || ', ' ||  COALESCE(TtsDiag.Diag_Code,'')  || '.' ||  COALESCE(TtsDiag.Diag_Name,'')
						 || ', Бригада №' ||  COALESCE(ET.EmergencyTeam_Num,'')
					else
						null
					end as SMMP_exists,
					COALESCE(CCC.CmpCallCard_Ngod::text,'') as EvnPS_CodeConv,
					COALESCE(ET.EmergencyTeam_Num,'') as EvnPS_NumConv,
					TTS.TimetableStac_updDT as TimetableStac_insDT,
					null as EvnQueue_setDate,
					null as EvnQueue_id,
					case when EvnPS.LpuSection_eid is not null then 2 else 1 end as IsHospitalized,
					EvnPS.EvnPS_id as EvnPS_id,
					EvnPS.EvnPS_IsActive as EvnPS_IsActive,
					EvnPS.EvnPS_setDT as EvnPS_setDT,
					datediff('minute', (select curDate from curDateTime), EvnPS.EvnPS_setDT) as EvnPS_setDT_Diff,
					EvnPS.EvnPS_NumCard as EvnPS_NumCard,
					TTS.TimetableStac_id as TimetableStac_id,
					TTSLS.LpuSectionProfile_Name as LpuSectionProfile_Name,
					TTSLS.LpuSectionProfile_id as LpuSectionProfile_did,
					EST.PrehospStatus_id as PrehospStatus_id,
					EST.PrehospStatus_Name as PrehospStatus_Name,
					Diag.Diag_id as Diag_id,
					RTRIM(coalesce(Diag.Diag_Code,TtsDiag.Diag_Code)) || '. ' || RTRIM(coalesce(Diag.Diag_Name,TtsDiag.Diag_Name)) as Diag_CodeName,
					puc.PMUser_Name as pmUser_Name,
					case when EvnPS.PrehospWaifRefuseCause_id is not null then 2 else 1 end as IsRefusal,
					EvnPS.PrehospWaifRefuseCause_id as PrehospWaifRefuseCause_id,
					COALESCE(EvnPS.EvnPS_IsTransfCall,1) as IsCall,
					COALESCE(EvnPS.EvnPS_IsPLAmbulance,1) as IsSmmp,
					PA.PrehospArrive_id as PrehospArrive_id,
					PA.PrehospArrive_SysNick as PrehospArrive_SysNick,
					PA.PrehospArrive_Name as PrehospArrive_Name,
					PT.PrehospType_id as PrehospType_id,
					PT.PrehospType_SysNick as PrehospType_SysNick,
					CASE
						WHEN EvnPS.PrehospDirect_id = 1 
						THEN TTSLSd.LpuSection_Name
						ELSE ORGd.Org_Name
					END as PrehospDirection_Name,
					
						to_char(PS.Person_Birthday, 'DD.MM.YYYY') as Person_BirthDay,
						
            case 
                
                when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) <= 31
                    then '' || datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) ||
                    case
                        when 
                            datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) >= 2
                            and datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) <= 4
                            or
                            datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) >= 22
                            and datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) + 1 <= 24
                        then ' дня'
                        when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) in (1, 21, 31)
                        then ' день'
                        else ' дней'
                    end
                when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) + 1 > 31 and dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) < 12
                    then '' || dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime))::varchar || ' мес.'
                    
                when dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) >= 12 and dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) < 36
                    then '' || dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar || 
                        case
                            when dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) = 2 then ' года '
                            else ' год '
                        end ||
                        case
                            when (dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) - (dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) * 12)) < 1 then ''
                            else (dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) - (dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) * 12))::varchar || ' мес.'
                        end
                        
                when dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) >= 3  
                    then '' || dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar || 
                        case
                    when 
                        right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,2)::integer >= 11 
                        and right(dbo.Age2(PS.Person_Birthday,(select curDate from curDateTime))::varchar,2)::integer <= 14 
                        or right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer >= 5 
                        and right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer <= 9 
                        or right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer = 0 
                    then ' лет' 
                    when 
                        right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer >= 2  
                        and right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer <= 4 
                    then ' года' 
                    when right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer = 1 
                    then ' год' 
                end
                    else '' || dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime))::varchar || ' мес.' 
            end 
            as Person_age
        ,
						COALESCE(PS.Person_SurName,'НЕИЗВЕСТЕН')  || ' ' ||  COALESCE(PS.Person_FirName,'НЕИЗВЕСТЕН')  || ' ' ||  COALESCE(PS.Person_SecName,'НЕИЗВЕСТЕН') as Person_Fio,
					null as PersonEncrypHIV_Encryp,
					PS.Person_id as Person_id,
					COALESCE(EvnPS.PersonEvn_id,PS.PersonEvn_id) as PersonEvn_id,
					COALESCE(EvnPS.Server_id,PS.Server_id) as Server_id,
					TTSLS.LpuSection_Name as LpuSection_Name,
					TTS.TimetableType_id as TimetableType_id,
					null as EmergencyDataStatus_id,
					TTS.Person_id as Person_ttsid,
					EvnPS.LpuSection_pid as LpuSection_pid,
					EvnPS.MedStaffFact_pid as MedStaffFact_pid,
					EvnPS.EvnPS_OutcomeDT as EvnPS_OutcomeDT,
					EvnPS.LpuSection_eid as LpuSection_eid,
					CCC.CmpCallCard_id as CmpCallCard_id,
					null as EvnSection_id,
					null as PayType_id,
					null as Person_IsBDZ,
					
					EPL.EvnPL_id as EvnPL_id,
					EPL.EvnPL_NumCard as EvnPL_NumCard,
					PS.Sex_id,
					PReg.PersonRegister_id,
					RTRIM(COALESCE(SST.SocStatus_Name, '')) as SocStatus_Name,
					CCC.CmpCallCard_EmgTeamComm as CmpCallCard_EmgTeamComm
				from v_TimetableStac_lite TTS 
					inner join v_PersonState PS  on TTS.Person_id = PS.Person_id
                    inner join v_LpuSection TTSLS on TTS.LpuSection_id = TTSLS.LpuSection_id
					left join v_SocStatus SST on SST.SocStatus_id = PS.SocStatus_id
					LEFT JOIN LATERAL (
						select 1 as EvnDirection_IsConfirmed
					) ED ON true
					left join v_EvnPS EvnPS  on TTS.Evn_id = EvnPS.EvnPS_id
					left join v_CmpCloseCardTimeTable CCCTT  on CCCTT.TimetableStac_id = TTS.TimetableStac_id
					left join v_CmpCallCard CCC  on CCC.CmpCallCard_id = CCCTT.CmpCallCard_id
					left join v_EmergencyTeam ET  on ET.EmergencyTeam_id = CCC.EmergencyTeam_id
					left join v_Diag Diag  on EvnPS.Diag_pid = Diag.Diag_id
					left join lateral (
						select *
						from v_Diag TtsDiag
						where TtsDiag.Diag_id = CCC.Diag_gid
						limit 1
					) TtsDiag on true
					left join v_PrehospStatus EST  on COALESCE(EvnPS.PrehospStatus_id,1) = EST.PrehospStatus_id
					left join v_PrehospArrive PA  on PA.PrehospArrive_id = EvnPS.PrehospArrive_id
					left join v_PrehospType PT  on PT.PrehospType_id = EvnPS.PrehospType_id
					left join pmUserCache puc  on TTS.pmUser_updId = puc.pmUser_id
					left join v_EvnLink EL  on EL.Evn_lid = EvnPS.EvnPS_id
					left join v_EvnPL EPL  on EPL.EvnPL_id = EL.Evn_id
					left join lateral (
						select PersonLpuInfo_IsAgree
						from v_PersonLpuInfo
						where Lpu_id = EvnPS.Lpu_id
							and Person_id = EvnPS.Person_id
						order by PersonLpuInfo_id desc
						limit 1
					) as PLI on true
					left join v_EvnDirection EDr  on EDr.EvnDirection_id = TTS.EvnDirection_id
					left join lateral (
						select
							PersonRegister_id,
							PersonPregnancy_id
						from
							v_PersonPregnancy
						where Person_id = PS.Person_id
						ORDER BY PersonPregnancy_id DESC
						limit 1
					) PReg on true
					left join v_LpuSection TTSLSd on EvnPS.LpuSection_did = TTSLSd.LpuSection_id
					left join v_Lpu LPUd on EvnPS.Lpu_did = LPUd.Lpu_id
					left join v_Org ORGd on EvnPS.Org_did = ORGd.Org_id
					
					
				where
					TTSLS.Lpu_id = (select LpuId from vars)
					AND TTS.Person_id is not null -- убрал некорректное отображение пустых бирок
					AND PS.Person_IsUnknown = 2
					AND EDr.EvnDirection_id is null -- здесь только без направлений
					AND EST.PrehospStatus_id = 1 -- со статусом не поступал
					
				AND TimetableStac_setDate >= '2022-01-22' and TimetableStac_setDate < '2022-01-23' -- если такой фильтр есть, то запрос можно сразу ограничить
					
					
					
			),
			tab2 as (
				
			select
				'EvnDirection_' ||  ED.EvnDirection_id::text as keyNote,
				TTS.TimetableStac_setDate as TimetableStac_setDate,
				ES.EvnStatus_SysNick as EvnStatus_SysNick,
				ED.EvnDirection_setDT as EvnDirection_setDT,
				ED.EvnDirection_id as EvnDirection_id,
				ED.EvnDirection_IsAuto as EvnDirection_IsAuto,
				ED.EvnDirection_insDT as EvnDirection_insDT,
				plia.PersonLpuInfo_IsAgree as PersonLpuInfo_IsAgree,
				ED.EvnDirection_IsConfirmed as EvnDirection_IsConfirmed,
				ED.EvnDirection_Num as EvnDirection_Num,
				to_char(cast(ED.EvnDirection_setDate as date), 'DD.MM.YYYY') as EvnDirection_setDate,
				ED.Diag_id as Diag_did,
				ED.LpuSection_id as LpuSection_did,
				TTSLSd.LpuSection_Name as LpuSection_dName,
				ED.Lpu_did,
				LPUd.Lpu_Name as Lpu_dName,
				ED.DirType_id as DirType_id,
				case when TTS.TimetableType_id = 6 then
						COALESCE(TTSLS.LpuSectionProfile_Name,'')
						 || ', ' ||  COALESCE(TtsDiag.Diag_Code,'')  || '.' ||  COALESCE(TtsDiag.Diag_Name,'')
						 || ', Бригада №' ||  COALESCE(ET.EmergencyTeam_Num,'')
					else
						null
					end as SMMP_exists,
				null as EvnPS_CodeConv,
				null as EvnPS_NumConv,
				null as TimetableStac_insDT,
				null as EvnQueue_setDate,
				null as EvnQueue_id,
				ED.TimetableStac_id as TimetableStac_id,
				ED.LpuSectionProfile_id as LpuSectionProfile_did,
				ED.Person_id as Person_id,
				ED.PersonEvn_id as PersonEvn_id,
				ED.Server_id as Server_id,
				null as childElement, 
				ED.LpuSectionProfile_id as LpuSectionProfile_id,
				ED.Diag_id as Diag_id,
				TTS.LpuSection_id as LpuSection_id,
				TTS.pmUser_updId as pmUser_updId,
				ED.pmUser_insID as pmUser_insID,
				COALESCE(ED.Lpu_sid,ED.Lpu_id) as Lpu_id,
				CCCTT.CmpCallCard_id as CmpCallCard_id,
				null as EvnSection_id,
				ED.PayType_id as PayType_id,
				null as Person_IsBDZ,
				null as PersonEncrypHIV_Encryp,
				
						PS.Person_Birthday as Person_BirthDay,
						
            case 
                
                when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) <= 31
                    then '' || datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) ||
                    case
                        when 
                            datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) >= 2
                            and datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) <= 4
                            or
                            datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) >= 22
                            and datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) + 1 <= 24
                        then ' дня'
                        when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) in (1, 21, 31)
                        then ' день'
                        else ' дней'
                    end
                when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) + 1 > 31 and dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) < 12
                    then '' || dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime))::varchar || ' мес.'
                    
                when dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) >= 12 and dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) < 36
                    then '' || dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar || 
                        case
                            when dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) = 2 then ' года '
                            else ' год '
                        end ||
                        case
                            when (dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) - (dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) * 12)) < 1 then ''
                            else (dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) - (dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) * 12))::varchar || ' мес.'
                        end
                        
                when dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) >= 3  
                    then '' || dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar || 
                        case
                    when 
                        right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,2)::integer >= 11 
                        and right(dbo.Age2(PS.Person_Birthday,(select curDate from curDateTime))::varchar,2)::integer <= 14 
                        or right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer >= 5 
                        and right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer <= 9 
                        or right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer = 0 
                    then ' лет' 
                    when 
                        right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer >= 2  
                        and right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer <= 4 
                    then ' года' 
                    when right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer = 1 
                    then ' год' 
                end
                    else '' || dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime))::varchar || ' мес.' 
            end 
            as Person_age
        ,
						PS.Person_Fio as Person_Fio,
				PS.Sex_id as Sex_id,
				PReg.PersonRegister_id as PersonRegister_id,
				RTRIM(COALESCE(SST.SocStatus_Name, '')) as SocStatus_Name,
				CCC.CmpCallCard_EmgTeamComm as "CmpCallCard_EmgTeamComm"
			from
				v_EvnDirection_all ED 
				inner join lateral (select * from v_Person_all PS where ED.Person_id = PS.Person_id and ED.PersonEvn_id = PS.PersonEvn_id and ED.Server_id = PS.Server_id limit 1) as PS on true
				left join v_SocStatus SST on SST.SocStatus_id = PS.SocStatus_id
				left join v_TimetableStac_lite TTS  on ED.TimetableStac_id = TTS.TimetableStac_id
				left join v_EvnStatus ES  on ES.EvnStatus_id = ED.EvnStatus_id
				left join v_LpuSection TTSLS  on TTS.LpuSection_id = TTSLS.LpuSection_id
				left join v_CmpCloseCardTimeTable CCCTT  on CCCTT.TimetableStac_id = TTS.TimetableStac_id
				left join v_CmpCallCard CCC  on CCC.CmpCallCard_id = CCCTT.CmpCallCard_id
				left join v_EmergencyTeam ET  on ET.EmergencyTeam_id = CCC.EmergencyTeam_id
				left join v_Diag TtsDiag  on TtsDiag.Diag_id = CCC.Diag_gid
				left join v_PrehospStatus EST  on 1 = EST.PrehospStatus_id
				left join v_LpuUnit LU  on ED.LpuUnit_did = LU.LpuUnit_id
				left join lateral (
					select
						plia.PersonLpuInfo_IsAgree
					from v_PersonLpuInfo plia
					where
						plia.Lpu_id = ED.Lpu_id
						and plia.Person_id = PS.Person_id
					order by plia.PersonLpuInfo_setDT desc
					limit 1
				) plia on true
				left join v_EvnPS EvnPS on TTS.Evn_id = EvnPS.EvnPS_id
				left join v_LpuSection TTSLSd on ED.LpuSection_id = TTSLSd.LpuSection_id
				left join v_Lpu LPUd on ED.Lpu_did = LPUd.Lpu_id
				left join lateral (
					select
						PersonRegister_id,
						PersonPregnancy_id
					from
						v_PersonPregnancy
					where Person_id = PS.Person_id
					ORDER BY PersonPregnancy_id DESC
					limit 1
				) PReg on true
				
			where
				ED.Lpu_did = (select LpuId from vars)
				AND ED.EvnQueue_id is null
				AND ( ED.DirType_id is not null AND ED.DirType_id in (1, 2, 4, 5, 6) )
				AND COALESCE(LU.LpuUnitType_SysNick,'stac')!='polka'
				AND (
					(COALESCE(ES.EvnStatus_SysNick, '') not in ('Canceled', 'Serviced', 'Declined') AND ED.DirFailType_id is NULL)
					OR
					(COALESCE(ES.EvnStatus_SysNick, '') in ('Declined') AND ED.DirFailType_id is NOT NULL)
				)
				
				
				
		 
			 	AND ((TTS.TimetableStac_setDate >= '2022-01-22' and TimetableStac_setDate < '2022-01-23')
			 	or (ED.DirType_id = 5 and ED.EvnDirection_setDT >= '2022-01-22' and ED.EvnDirection_setDT < '2022-01-23'))
			), mv as (
				select
					cast('2022-01-22' as timestamp) as dt
			)
			select
				'EvnDirection_' ||  ED.EvnDirection_id::text as "keyNote",
				to_char( coalesce (EvnPS.EvnPS_setDate, ED.TimetableStac_setDate, ED.EvnDirection_setDT), 'yyyymmdd') as "sortDate",
				CASE WHEN ED.EvnStatus_SysNick = 'Declined' THEN 5 ELSE 1 END as "groupField",
				ED.EvnDirection_id as "EvnDirection_id",
				ED.EvnDirection_IsAuto as "EvnDirection_IsAuto",
				to_char(ED.EvnDirection_insDT, 'DD.MM.YYYY') as "EvnDirection_insDT",
				PLI.PersonLpuInfo_IsAgree as "PersonLpuInfo_IsAgree",
				ED.EvnDirection_IsConfirmed as "EvnDirection_IsConfirmed",
				ED.EvnDirection_Num as "EvnDirection_Num",
				to_char(cast(ED.EvnDirection_setDate as date), 'DD.MM.YYYY') as "EvnDirection_setDate",
				ED.Diag_id as "Diag_did",
				ED.LpuSection_did as "LpuSection_did",
				TTSLSd.LpuSection_Name as "LpuSection_dName",
				L.Lpu_id as "Lpu_did",
				LPUd.Lpu_Name as "Lpu_dName",
				L.Org_id as "Org_did",
				ORGd.Org_Name as "Org_dName",	
				ED.DirType_id as "DirType_id",
				COALESCE(DT.DirType_Name,'')  || ', ' ||  COALESCE(LSP.LpuSectionProfile_Name,'')  || ', ' ||  COALESCE(DiagD.Diag_Code,'') || '.' ||  COALESCE(DiagD.Diag_Name,'') as "Direction_exists",
				to_char(ED.TimetableStac_setDate, 'DD.MM.YYYY') || ' ' || to_char(ED.TimetableStac_setDate, 'HH24:MI') as "TimetableStac_setDate",
				SMMP_exists as "SMMP_exists",
				null as "EvnPS_CodeConv",
				null as "EvnPS_NumConv",
				null as "TimetableStac_insDT",
				null as "EvnQueue_setDate",
				null as "EvnQueue_id",
				case when EvnPS.LpuSection_eid is not null then 2 else 1 end as "IsHospitalized",
				EvnPS.EvnPS_id as "EvnPS_id",
				EvnPS.EvnPS_IsActive as "EvnPS_IsActive",
				to_char(EvnPS.EvnPS_setDT, 'DD.MM.YYYY HH24:MI') as "EvnPS_setDT",--Дата/время поступления;  если есть КВС
				datediff('minute', (select curDate from curDateTime), EvnPS.EvnPS_setDT) as "EvnPS_setDT_Diff",
				EvnPS.EvnPS_NumCard as "EvnPS_NumCard",
				ED.TimetableStac_id as "TimetableStac_id",
				LSP.LpuSectionProfile_Name as "LpuSectionProfile_Name",
				ED.LpuSectionProfile_id as "LpuSectionProfile_did",
				CASE WHEN ED.EvnStatus_SysNick = 'Declined' THEN 5 ELSE 1 END as "PrehospStatus_id",
				CASE WHEN ED.EvnStatus_SysNick = 'Declined' THEN 'Отказ' ELSE 'Не поступал' END as "PrehospStatus_Name",
				Diag.Diag_id as "Diag_id",
				RTRIM(Diag.Diag_Code) || '. ' || RTRIM(Diag.Diag_Name) as "Diag_CodeName",
				puc.PMUser_Name as "pmUser_Name", --pmUser_Name Оператор. (направления/бирки, как в АРМ поликлиники)
				case when EvnPS.PrehospWaifRefuseCause_id is not null then 2 else 1 end as "IsRefusal",-- признак наличия отказа
				EvnPS.PrehospWaifRefuseCause_id as "PrehospWaifRefuseCause_id",
				EvnPS.MedStaffFact_pid as "MedStaffFact_pid",
				COALESCE(EvnPS.EvnPS_IsTransfCall,1) as "IsCall", -- Передан активный вызов
				COALESCE(EvnPS.EvnPS_IsPLAmbulance,1) as "IsSmmp", -- Талон передан на ССМП
				PA.PrehospArrive_id as "PrehospArrive_id",
				PA.PrehospArrive_SysNick as "PrehospArrive_SysNick",
				PA.PrehospArrive_Name as "PrehospArrive_Name",
				PT.PrehospType_id as "PrehospType_id",
				PT.PrehospType_SysNick as "PrehospType_SysNick",
				CASE
					WHEN EvnPS.PrehospDirect_id = 1
					THEN TTSLSd.LpuSection_Name
					ELSE ORGd.Org_Name
				END as "PrehospDirection_Name",
				to_char(ED.Person_Birthday, 'DD.MM.YYYY') as "Person_BirthDay",
				ED.Person_age as "Person_age",
				ED.Person_Fio as "Person_Fio",
				ED.PersonEncrypHIV_Encryp as "PersonEncrypHIV_Encryp",
				ED.Person_id as "Person_id",
				ED.PersonEvn_id as "PersonEvn_id",
				ED.Server_id as "Server_id",
				null as "childElement",
				LS.LpuSection_Name as "LpuSection_Name",
				EPL.EvnPL_id as "EvnPL_id",
				EPL.EvnPL_NumCard as "EvnPL_NumCard",
				ED.CmpCallCard_id as "CmpCallCard_id",
				cast(null as bigint) as "EvnSection_id",
				ED.PayType_id as "PayType_id",
				Person_IsBDZ as "Person_IsBDZ",
				case when exists(
					select *
					from v_PersonQuarantine PQ
					where PQ.Person_id = ED.Person_id
					and PQ.PersonQuarantine_endDT is null
				) then 2 else 1 end as "PersonQuarantine_IsOn",
				
				to_char(EvnPS.EvnPS_OutcomeDT, 'DD.MM.YYYY HH24:MI') as "EvnPS_OutcomeDT",
				ED.Sex_id as "Sex_id",
				PReg.PersonRegister_id as "PersonRegister_id",
				ED.SocStatus_Name as "SocStatus_Name",
				null as "CmpCallCard_EmgTeamComm"
			from
				tab2 ED 
				left join v_EvnPS EvnPS  on ED.EvnDirection_id = EvnPS.EvnDirection_id
				left join v_DirType DT  on ED.DirType_id = DT.DirType_id
				left join v_LpuSectionProfile LSP  on ED.LpuSectionProfile_id = LSP.LpuSectionProfile_id
				left join v_Diag DiagD  on ED.Diag_id= DiagD.Diag_id
				left join v_LpuSection LS  on COALESCE(EvnPS.LpuSection_eid,ED.LpuSection_id,ED.LpuSection_did) = LS.LpuSection_id
				left join v_Diag Diag  on COALESCE(EvnPS.Diag_pid,ED.Diag_id) = Diag.Diag_id
				left join pmUserCache puc  on COALESCE (ED.pmUser_updId, ED.pmUser_insID) = puc.pmUser_id
				left join v_Lpu L  on L.Lpu_id = ED.Lpu_id
				left join v_EvnLink EL  on EL.Evn_lid = EvnPS.EvnPS_id
				left join v_EvnPL EPL  on EPL.EvnPL_id = EL.Evn_id
				left join v_PrehospArrive PA  on PA.PrehospArrive_id = EvnPS.PrehospArrive_id
				left join v_PrehospType PT  on PT.PrehospType_id = EvnPS.PrehospType_id
				left join lateral (
					select
						PersonRegister_id,
						PersonPregnancy_id
					from
						v_PersonPregnancy
					where Person_id = ED.Person_id
					ORDER BY PersonPregnancy_id DESC
					limit 1
				) PReg on true
				left join lateral (
					select PersonLpuInfo_IsAgree
					from v_PersonLpuInfo
					where Lpu_id = EvnPS.Lpu_id
						and Person_id = EvnPS.Person_id
					order by PersonLpuInfo_id desc
					limit 1
				) as PLI on true
				left join v_LpuSection TTSLSd on ED.LpuSection_did = TTSLSd.LpuSection_id
				left join v_Lpu LPUd on L.Lpu_id = LPUd.Lpu_id
				left join v_Org ORGd on L.Org_id = ORGd.Org_id
				
			where
				(1=1) and COALESCE(EvnPS.PrehospStatus_id,1) in (1)
				
			union all
			select
				'EvnQueue_' || EQ.EvnQueue_id::text as "keyNote",
				to_char(EQ.EvnQueue_setDT, 'YYYYMMDD') as "sortDate",
				EST.PrehospStatus_id as "groupField",
				EQ.EvnDirection_id as "EvnDirection_id",
				ED.EvnDirection_IsAuto as "EvnDirection_IsAuto",
				to_char(EQ.EvnQueue_insDT, 'DD.MM.YYYY') as "EvnDirection_insDT",
				v_PersonLpuInfo.PersonLpuInfo_IsAgree as "PersonLpuInfo_IsAgree",
				ED.EvnDirection_IsConfirmed as "EvnDirection_IsConfirmed",
				ED.EvnDirection_Num as "EvnDirection_Num",
				to_char(ED.EvnDirection_setDT, 'DD.MM.YYYY') as "EvnDirection_setDate",
				ED.Diag_id as "Diag_did",
				ED.LpuSection_id as "LpuSection_did",
				TTSLSd.LpuSection_Name as "LpuSection_dName",
				L.Lpu_id as "Lpu_did",
				LPUd.Lpu_Name as "Lpu_dName",
				L.Org_id as "Org_did",
				ORGd.Org_Name as "Org_dName",
				ED.DirType_id as "DirType_id",
				COALESCE(DT.DirType_Name,'')  || ', ' ||  COALESCE(LSP.LpuSectionProfile_Name,'')  || ', ' ||  COALESCE(Diag.Diag_Code,'') || '.' ||  COALESCE(Diag.Diag_Name,'') as "Direction_exists",
				null as "TimetableStac_setDate",
				null as "SMMP_exists",
				null as "EvnPS_CodeConv",
				null as "EvnPS_NumConv",
				null as "TimetableStac_insDT",
				to_char(EQ.EvnQueue_setDT, 'DD.MM.YYYY') as "EvnQueue_setDate",
				EQ.EvnQueue_id as "EvnQueue_id",
				1 as "IsHospitalized",
				null as "EvnPS_id",
				EvnPS.EvnPS_IsActive as "EvnPS_IsActive",
				'' as "EvnPS_setDT",
				0 as "EvnPS_setDT_Diff",
				null as "EvnPS_NumCard",
				EQ.TimetableStac_id as "TimetableStac_id",
				LSP.LpuSectionProfile_Name as "LpuSectionProfile_Name",
				EQ.LpuSectionProfile_did as "LpuSectionProfile_did",
				EST.PrehospStatus_id as "PrehospStatus_id",
				EST.PrehospStatus_Name as "PrehospStatus_Name",
				Diag.Diag_id as "Diag_id",
				RTRIM(Diag.Diag_Code) || '. ' || RTRIM(Diag.Diag_Name) as "Diag_CodeName",
				puc.PMUser_Name as "pmUser_Name",
				1 as "IsRefusal",
				null as "PrehospWaifRefuseCause_id",
				null as "MedStaffFact_pid",
				1 as "IsCall",
				1 as "IsSmmp",
				null as "PrehospArrive_id",
				null as "PrehospArrive_SysNick",
				null as "PrehospArrive_Name",
				null as "PrehospType_id",
				null as "PrehospType_SysNick",
				CASE
					WHEN EvnPS.PrehospDirect_id = 1
					THEN TTSLSd.LpuSection_Name
					ELSE ORGd.Org_Name
				END as "PrehospDirection_Name",
				
						to_char(PS.Person_Birthday, 'DD.MM.YYYY') as "Person_BirthDay",
						
            case 
                
                when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) <= 31
                    then '' || datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) ||
                    case
                        when 
                            datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) >= 2
                            and datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) <= 4
                            or
                            datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) >= 22
                            and datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) + 1 <= 24
                        then ' дня'
                        when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) in (1, 21, 31)
                        then ' день'
                        else ' дней'
                    end
                when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) + 1 > 31 and dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) < 12
                    then '' || dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime))::varchar || ' мес.'
                    
                when dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) >= 12 and dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) < 36
                    then '' || dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar || 
                        case
                            when dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) = 2 then ' года '
                            else ' год '
                        end ||
                        case
                            when (dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) - (dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) * 12)) < 1 then ''
                            else (dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) - (dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) * 12))::varchar || ' мес.'
                        end
                        
                when dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) >= 3  
                    then '' || dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar || 
                        case
                    when 
                        right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,2)::integer >= 11 
                        and right(dbo.Age2(PS.Person_Birthday,(select curDate from curDateTime))::varchar,2)::integer <= 14 
                        or right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer >= 5 
                        and right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer <= 9 
                        or right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer = 0 
                    then ' лет' 
                    when 
                        right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer >= 2  
                        and right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer <= 4 
                    then ' года' 
                    when right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer = 1 
                    then ' год' 
                end
                    else '' || dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime))::varchar || ' мес.' 
            end 
            as "Person_age"
        ,
						PS.Person_Fio as "Person_Fio",
				null as "PersonEncrypHIV_Encryp",
				EQ.Person_id as "Person_id",
				EQ.PersonEvn_id as "PersonEvn_id",
				EQ.Server_id as "Server_id",
				null as "childElement",
				LS.LpuSection_Name as "LpuSection_Name",
				null as "EvnPL_id",
				null as "EvnPL_NumCard",
				EvnPS.CmpCallCard_id as "CmpCallCard_id",
				cast(null as bigint) as "EvnSection_id",
				ED.PayType_id as "PayType_id",
				null as "Person_IsBDZ",
				case when exists(
					select *
					from v_PersonQuarantine PQ
					where PQ.Person_id = EQ.Person_id
					and PQ.PersonQuarantine_endDT is null
				) then 2 else 1 end as "PersonQuarantine_IsOn",
				
				'' as "EvnPS_OutcomeDT",
				PS.Sex_id as "Sex_id",
				PReg.PersonRegister_id as "PersonRegister_id",
				RTRIM(COALESCE(SST.SocStatus_Name, '')) as "SocStatus_Name",
				CCC.CmpCallCard_EmgTeamComm as "CmpCallCard_EmgTeamComm"
			from v_EvnDirection_all ED 
				inner join  v_EvnQueue EQ  on EQ.EvnDirection_id = ED.EvnDirection_id and EQ.EvnQueue_id = ED.EvnQueue_id
				inner join lateral (select * from v_Person_all PS where EQ.Person_id = PS.Person_id and EQ.PersonEvn_id = PS.PersonEvn_id and EQ.Server_id = PS.Server_id limit 1) as PS on true
				left join v_SocStatus SST on SST.SocStatus_id = PS.SocStatus_id
				left join v_LpuUnit LU  on EQ.LpuUnit_did = LU.LpuUnit_id
				left join v_DirType DT  on ED.DirType_id = DT.DirType_id
				left join v_LpuSectionProfile LSP  on EQ.LpuSectionProfile_did = LSP.LpuSectionProfile_id
				left join lateral(
					select *
					from v_Diag Diag
					where COALESCE(EQ.Diag_id, ED.Diag_id) = Diag.Diag_id
					limit 1
				) Diag on true
				left join v_PrehospStatus EST  on EST.PrehospStatus_id =  CASE WHEN coalesce(ED.EvnDirection_failDT, ED.EvnDirection_statusDate) IS NOT NULL AND ED.EvnStatus_id = 13 THEN 5 ELSE 1 END
				left join pmUserCache puc  on EQ.pmUser_insID = puc.pmUser_id
				left join v_Lpu L  on L.Lpu_id = COALESCE(ED.Lpu_sid,ED.Lpu_id)
                left join v_EvnPS EvnPS  on EvnPS.EvnDirection_id = ED.EvnDirection_id
                left join v_CmpCallCard CCC on CCC.CmpCallCard_id = EvnPS.CmpCallCard_id
				left join v_LpuSection LS  on LS.LpuSection_id = ED.LpuSection_did
				-- нет смысла брать согласие с КВС, при условии в фильтрах AND EvnPS.EvnPS_id is null
                left join v_PersonLpuInfo  on ED.Lpu_id = v_PersonLpuInfo.Lpu_id and ED.Person_id = v_PersonLpuInfo.Person_id
				left join v_LpuSection TTSLSd on ED.LpuSection_did = TTSLSd.LpuSection_id
				left join v_Lpu LPUd on L.Lpu_id = LPUd.Lpu_id
				left join v_Org ORGd on L.Org_id = ORGd.Org_id
				left join lateral (
					select
						PersonRegister_id,
						PersonPregnancy_id
					from
						v_PersonPregnancy
					where Person_id = PS.Person_id
					ORDER BY PersonPregnancy_id DESC
					limit 1
				) PReg on true
				
				
			where
				(1=2) AND 
				--EQ.EvnQueue_failDT is null
                (EQ.EvnQueue_failDT is NULL OR ED.EvnStatus_id = 13 AND (select dt
                                                                         from mv) = CAST(ED.EvnDirection_failDT AS DATE) --показывать в группе ОТКАЗ со статусом отклонено
                )

				AND EQ.EvnQueue_recDT is null
				AND ED.EvnStatus_id not in (8, 15, 17)
				
				AND ED.Lpu_did = (select LpuId from vars) -- по идее очередь куда поставили и направление куда направили, должны быть в одну МО
				AND (EQ.EvnDirection_id is null OR EQ.EvnQueue_id is not null)
				AND ED.DirType_id IN (1,2,5,4,6)
				
				
				

			union all

			select
				keyNote as "keyNote",
				to_char(sortDate, 'YYYYMMDD') as "sortDate",
				groupField as "groupField",
				cast(EvnDirection_id as bigint) as "EvnDirection_id",
				cast(EvnDirection_IsAuto as bigint) as "EvnDirection_IsAuto",
				to_char(EvnDirection_insDT, 'DD.MM.YYYY') as "EvnDirection_insDT",
				PersonLpuInfo_IsAgree as "PersonLpuInfo_IsAgree",
				cast(EvnDirection_IsConfirmed as bigint) as "EvnDirection_IsConfirmed",
				EvnDirection_Num as "EvnDirection_Num",
				to_char(EvnDirection_setDate, 'DD.MM.YYYY') as "EvnDirection_setDate",
				Diag_did as "Diag_did",
				LpuSection_did as "LpuSection_did",
				LpuSection_dName as "LpuSection_dName",
				Lpu_did as "Lpu_did",
				Lpu_dName as "Lpu_dName",
				Org_did as "Org_did",
				Org_dName as "Org_dName",
				cast(DirType_id as bigint) as "DirType_id",
				Direction_exists as "Direction_exists",
				to_char(TimetableStac_setDate, 'DD.MM.YYYY') || ' ' || to_char(TimetableStac_setDate, 'HH24:MI') as "TimetableStac_setDate",
				SMMP_exists as "SMMP_exists",
				EvnPS_CodeConv as "EvnPS_CodeConv",
				EvnPS_NumConv as "EvnPS_NumConv",
				to_char(TimetableStac_insDT, 'DD.MM.YYYY HH24:MI') as "TimetableStac_insDT",
				EvnQueue_setDate as "EvnQueue_setDate",
				null as "EvnQueue_id",
				IsHospitalized as "IsHospitalized",
				EvnPS_id as "EvnPS_id",
				EvnPS_IsActive as "EvnPS_IsActive",
				to_char(EvnPS_setDT, 'DD.MM.YYYY HH24:MI') as "EvnPS_setDT",
				datediff('minute', (select curDate from curDateTime), EvnPS_setDT) as "EvnPS_setDT_Diff",
				EvnPS_NumCard as "EvnPS_NumCard",
				TimetableStac_id as "TimetableStac_id",
				LpuSectionProfile_Name as "LpuSectionProfile_Name",
				LpuSectionProfile_did as "LpuSectionProfile_did",
				PrehospStatus_id as "PrehospStatus_id",
				PrehospStatus_Name as "PrehospStatus_Name",
				Diag_id as "Diag_id",
				Diag_CodeName as "Diag_CodeName",
				pmUser_Name as "pmUser_Name",
				IsRefusal as "IsRefusal",
				PrehospWaifRefuseCause_id as "PrehospWaifRefuseCause_id",
				MedStaffFact_pid as "MedStaffFact_pid",
				IsCall as "IsCall",
				IsSmmp as "IsSmmp",
				PrehospArrive_id as "PrehospArrive_id",
				PrehospArrive_SysNick as "PrehospArrive_SysNick",
				PrehospArrive_Name as "PrehospArrive_Name",
				PrehospType_id as "PrehospType_id",
				PrehospType_SysNick as "PrehospType_SysNick",
				PrehospDirection_Name as "PrehospDirection_Name",
				to_char(cast(Person_Birthday as date), 'DD.MM.YYYY') as "Person_BirthDay",
				Person_age as "Person_age",
				Person_Fio as "Person_Fio",
				PersonEncrypHIV_Encryp as "PersonEncrypHIV_Encryp",
				Person_id as "Person_id",
				PersonEvn_id as "PersonEvn_id",
				Server_id as "Server_id",
				null as "childElement",
				LpuSection_Name as "LpuSection_Name",
				EvnPL_id as "EvnPL_id",
				EvnPL_NumCard as "EvnPL_NumCard",
				CmpCallCard_id as "CmpCallCard_id",
				cast(null as bigint) as "EvnSection_id",
				cast(PayType_id as bigint) as "PayType_id",
				Person_IsBDZ as "Person_IsBDZ",
				case when exists(
					select *
					from v_PersonQuarantine PQ
					where PQ.Person_id = Person_id
					and PQ.PersonQuarantine_endDT is null
				) then 2 else 1 end as "PersonQuarantine_IsOn",
				
				to_char(EvnPS_OutcomeDT, 'DD.MM.YYYY HH24:MI') as "EvnPS_OutcomeDT",
				Sex_id as "Sex_id",
				PersonRegister_id as "PersonRegister_id",
				SocStatus_Name as "SocStatus_Name",
				CmpCallCard_EmgTeamComm as "CmpCallCard_EmgTeamComm"
			from tab1 
			where
				-- экстр. бирки только с EmergencyDataStatus Койка забронирована на установленную дату
				-- /*AND EmergencyDataStatus_id = 1 */ - описание в комите к #51610
				(TimetableType_id = 6 AND cast(TimetableStac_setDate as date) = (select dt from mv) /*AND EmergencyDataStatus_id = 1 */)

			union all

			select
				keyNote as "keyNote",
				to_char(sortDate, 'YYYYMMDD') as "sortDate",
				groupField as "groupField",
				cast(EvnDirection_id as bigint) as "EvnDirection_id",
				cast(EvnDirection_IsAuto as bigint) as "EvnDirection_IsAuto",
				to_char(EvnDirection_insDT, 'DD.MM.YYYY') as "EvnDirection_insDT",
				PersonLpuInfo_IsAgree as "PersonLpuInfo_IsAgree",
				cast(EvnDirection_IsConfirmed as bigint) as "EvnDirection_IsConfirmed",
				EvnDirection_Num as "EvnDirection_Num",
				to_char(EvnDirection_setDate, 'DD.MM.YYYY') as "EvnDirection_setDate",
				Diag_did as "Diag_did",
				LpuSection_did as "LpuSection_did",
				LpuSection_dName as "LpuSection_dName",
				Lpu_did as "Lpu_did",
				Lpu_dName as "Lpu_dName",
				Org_did as "Org_did",
				Org_dName as "Org_dName",
				cast(DirType_id as bigint) as "DirType_id",
				Direction_exists as "Direction_exists",
				to_char(TimetableStac_setDate, 'DD.MM.YYYY') || ' ' || to_char(TimetableStac_setDate, 'HH24:MI') as "TimetableStac_setDate",
				SMMP_exists as "SMMP_exists",
				EvnPS_CodeConv as "EvnPS_CodeConv",
				EvnPS_NumConv as "EvnPS_NumConv",
				to_char(TimetableStac_insDT, 'DD.MM.YYYY HH24:MI') as "TimetableStac_insDT",
				EvnQueue_setDate as "EvnQueue_setDate",
				cast(EvnQueue_id as bigint) as "EvnQueue_id",
				IsHospitalized as "IsHospitalized",
				EvnPS_id as "EvnPS_id",
				EvnPS_IsActive as "EvnPS_IsActive",
				to_char(EvnPS_setDT, 'DD.MM.YYYY HH24:MI') as "EvnPS_setDT",
				datediff('minute', (select curDate from curDateTime), EvnPS_setDT) as "EvnPS_setDT_Diff",
				EvnPS_NumCard as "EvnPS_NumCard",
				TimetableStac_id as "TimetableStac_id",
				LpuSectionProfile_Name as "LpuSectionProfile_Name",
				LpuSectionProfile_did as "LpuSectionProfile_did",
				PrehospStatus_id as "PrehospStatus_id",
				PrehospStatus_Name as "PrehospStatus_Name",
				Diag_id as "Diag_id",
				Diag_CodeName as "Diag_CodeName",
				pmUser_Name as "pmUser_Name",
				IsRefusal as "IsRefusal",
				PrehospWaifRefuseCause_id as "PrehospWaifRefuseCause_id",
				MedStaffFact_pid as "MedStaffFact_pid",
				IsCall as "IsCall",
				IsSmmp as "IsSmmp",
				PrehospArrive_id as "PrehospArrive_id",
				PrehospArrive_SysNick as "PrehospArrive_SysNick",
				PrehospArrive_Name as "PrehospArrive_Name",
				PrehospType_id as "PrehospType_id",
				PrehospType_SysNick as "PrehospType_SysNick",
				PrehospDirection_Name as "PrehospDirection_Name",
				to_char(cast(Person_Birthday as date), 'DD.MM.YYYY') as "Person_BirthDay",
				Person_age as "Person_age",
				Person_Fio as "Person_Fio",
				PersonEncrypHIV_Encryp as "PersonEncrypHIV_Encryp",
				Person_id as "Person_id",
				PersonEvn_id as "PersonEvn_id",
				Server_id as "Server_id",
				null as "childElement",
				LpuSection_Name as "LpuSection_Name",
				EvnPL_id as "EvnPL_id",
				EvnPL_NumCard as "EvnPL_NumCard",
				CmpCallCard_id as "CmpCallCard_id",
				cast(null as bigint) as "EvnSection_id",
				cast(PayType_id as bigint) as "PayType_id",
				Person_IsBDZ as "Person_IsBDZ",
				case when exists(
					select *
					from v_PersonQuarantine PQ
					where PQ.Person_id = Person_id
					and PQ.PersonQuarantine_endDT is null
				) then 2 else 1 end as "PersonQuarantine_IsOn",
				
				to_char(EvnPS_OutcomeDT, 'DD.MM.YYYY HH24:MI') as "EvnPS_OutcomeDT",
				Sex_id as "Sex_id",
				PersonRegister_id as "PersonRegister_id",
				SocStatus_Name as "SocStatus_Name",
				CmpCallCard_EmgTeamComm as "CmpCallCard_EmgTeamComm"
			from tab1 
			where
				-- в зависимости от фильтра: все или на установленную дату
				(TimetableType_id != 6 AND Person_ttsid is not null 
                
				AND TimetableStac_setDate >= '2022-01-22' and TimetableStac_setDate < '2022-01-23'
                )

			union all

			select
				'EvnPS_' || EvnPS.EvnPS_id::text as "keyNote",
				to_char(EvnPS.EvnPS_setDate, 'YYYYMMDD') as "sortDate",
				case 
					when EvnPS.EvnPS_setDate <= (select dt from mv) and datediff('day', EvnPS.EvnPS_setDate, (select dt from mv)) < 3 and coalesce(cast(EvnPS.EvnPS_OutcomeDT as date), Child.EvnSection_setDate, ((select dt from mv) + interval '1 day')) > (select dt from mv) then EST.PrehospStatus_id
					when (cast(EvnPS.EvnPS_OutcomeDT as date) = (select dt from mv) AND EvnPS.LpuSection_eid IS NOT NULL) then 4
					
					when cast(EvnPS.EvnPS_OutcomeDT as date) = (select dt from mv) AND EvnPS.PrehospWaifRefuseCause_id IS NOT NULL then 5
					when ED.EvnStatus_id = 13 AND ED.EvnDirection_failDT IS NOT NULL AND (select dt from mv) = CAST(ED.EvnDirection_failDT AS DATE) then 5
					else EST.PrehospStatus_id
				end as "groupField",
				ED.EvnDirection_id as "EvnDirection_id",
				ED.EvnDirection_IsAuto as "EvnDirection_IsAuto",
				to_char(ED.EvnDirection_insDT, 'DD.MM.YYYY') as "EvnDirection_insDT",
				PLI.PersonLpuInfo_IsAgree as "PersonLpuInfo_IsAgree",
				ED.EvnDirection_IsConfirmed as "EvnDirection_IsConfirmed",
				EvnPS.EvnDirection_Num as "EvnDirection_Num",
				to_char(EvnPS.EvnDirection_setDT, 'DD.MM.YYYY') as "EvnDirection_setDate",
				EvnPS.Diag_did as "Diag_did",
				EvnPS.LpuSection_did as "LpuSection_did",
				TTSLSd.LpuSection_Name as "LpuSection_dName",
				EvnPS.Lpu_did as "Lpu_did",
				LPUd.Lpu_Name as "Lpu_dName",
				EvnPS.Org_did as "Org_did",
				ORGd.Org_Name as "Org_dName",
				ED.DirType_id as "DirType_id",
				COALESCE(DT.DirType_Name,'')  || ', ' ||  COALESCE(LSP.LpuSectionProfile_Name,'')  || ', ' ||  COALESCE(DiagD.Diag_Code,'') || '.' ||  COALESCE(DiagD.Diag_Name,'') as "Direction_exists",
				to_char(TTS.TimetableStac_setDate, 'DD.MM.YYYY') || ' ' || to_char(TTS.TimetableStac_setDate, 'HH24:MI') as "TimetableStac_setDate",
				null as "SMMP_exists",
				null as "EvnPS_CodeConv",
				null as "EvnPS_NumConv",
				null as "TimetableStac_insDT",
				null as "EvnQueue_setDate",
				null as "EvnQueue_id",
				case when EvnPS.LpuSection_eid is not null then 2 else 1 end as "IsHospitalized",
				EvnPS.EvnPS_id as "EvnPS_id",
				EvnPS.EvnPS_IsActive as "EvnPS_IsActive",
				to_char(EvnPS.EvnPS_setDT, 'DD.MM.YYYY HH24:MI') as "EvnPS_setDT",--Дата/время поступления;  если есть КВС
				datediff('minute', (select curDate from curDateTime), EvnPS.EvnPS_setDT) as "EvnPS_setDT_Diff",
				EvnPS_NumCard as "EvnPS_NumCard",
				TTS.TimeTableStac_id as "TimetableStac_id",
				'' as "LpuSectionProfile_Name",
				ED.LpuSectionProfile_id as "LpuSectionProfile_did",
				EST.PrehospStatus_id as "PrehospStatus_id",
				case 
					when EvnPS.EvnPS_setDate <= (select dt from mv) and datediff('day', EvnPS.EvnPS_setDate, (select dt from mv)) < 3 and coalesce(cast(EvnPS.EvnPS_OutcomeDT as date), Child.EvnSection_setDate, ((select dt from mv) + interval '1 day')) > (select dt from mv) then EST.PrehospStatus_Name
					when cast(EvnPS.EvnPS_OutcomeDT as date) = (select dt from mv) AND EvnPS.LpuSection_eid IS NOT NULL then 'Госпитализирован'
					
					when cast(EvnPS.EvnPS_OutcomeDT as date) = (select dt from mv) AND EvnPS.PrehospWaifRefuseCause_id IS NOT NULL then 'Отказ'
					else EST.PrehospStatus_Name
				end as "PrehospStatus_Name",
				Diag.Diag_id as "Diag_id",
				RTRIM(Diag.Diag_Code) || '. ' || RTRIM(Diag.Diag_Name) as "Diag_CodeName",--Диагноз приемного; код, наименование
				puc.PMUser_Name as "pmUser_Name",
				case when EvnPS.PrehospWaifRefuseCause_id is not null then 2 else 1 end as "IsRefusal",-- признак наличия отказа
				EvnPS.PrehospWaifRefuseCause_id as "PrehospWaifRefuseCause_id",
				EvnPS.MedStaffFact_pid as "MedStaffFact_pid",
				COALESCE(EvnPS.EvnPS_IsTransfCall,1) as "IsCall", -- Передан активный вызов
				COALESCE(EvnPS.EvnPS_IsPLAmbulance,1) as "IsSmmp", -- Талон передан на ССМП
				PA.PrehospArrive_id as "PrehospArrive_id",
				PA.PrehospArrive_SysNick as "PrehospArrive_SysNick",
				PA.PrehospArrive_Name as "PrehospArrive_Name",
				PT.PrehospType_id as "PrehospType_id",
				PT.PrehospType_SysNick as "PrehospType_SysNick",
				CASE
					WHEN EvnPS.PrehospDirect_id = 1
					THEN TTSLSd.LpuSection_Name
					ELSE ORGd.Org_Name
				END as "PrehospDirection_Name",
				
						to_char(PS.Person_Birthday, 'DD.MM.YYYY') as "Person_BirthDay",
						
            case 
                
                when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) <= 31
                    then '' || datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) ||
                    case
                        when 
                            datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) >= 2
                            and datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) <= 4
                            or
                            datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) >= 22
                            and datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) + 1 <= 24
                        then ' дня'
                        when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) in (1, 21, 31)
                        then ' день'
                        else ' дней'
                    end
                when datediff('day', PS.Person_Birthday, (select curDate from curDateTime)) + 1 > 31 and dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) < 12
                    then '' || dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime))::varchar || ' мес.'
                    
                when dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) >= 12 and dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) < 36
                    then '' || dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar || 
                        case
                            when dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) = 2 then ' года '
                            else ' год '
                        end ||
                        case
                            when (dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) - (dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) * 12)) < 1 then ''
                            else (dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime)) - (dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) * 12))::varchar || ' мес.'
                        end
                        
                when dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime)) >= 3  
                    then '' || dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar || 
                        case
                    when 
                        right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,2)::integer >= 11 
                        and right(dbo.Age2(PS.Person_Birthday,(select curDate from curDateTime))::varchar,2)::integer <= 14 
                        or right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer >= 5 
                        and right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer <= 9 
                        or right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer = 0 
                    then ' лет' 
                    when 
                        right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer >= 2  
                        and right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer <= 4 
                    then ' года' 
                    when right(dbo.Age2(PS.Person_Birthday, (select curDate from curDateTime))::varchar,1)::integer = 1 
                    then ' год' 
                end
                    else '' || dbo.Age_newborn(PS.Person_Birthday, (select curDate from curDateTime))::varchar || ' мес.' 
            end 
            as "Person_age"
        ,
						PS.Person_Fio as "Person_Fio",
				null as "PersonEncrypHIV_Encryp",
				EvnPS.Person_id as "Person_id",
				EvnPS.PersonEvn_id as "PersonEvn_id",
				EvnPS.Server_id as "Server_id",
				Child.ChildEvn_id::text as "childElement",
				LS.LpuSection_Name as "LpuSection_Name",
				EPL.EvnPL_id as "EvnPL_id",
				EPL.EvnPL_NumCard as "EvnPL_NumCard",
				EvnPS.CmpCallCard_id as "CmpCallCard_id",
				EvnSection.EvnSection_id as "EvnSection_id",
				cast(null as bigint) as "PayType_id",
				null as "Person_IsBDZ",
				case when exists(
					select *
					from v_PersonQuarantine PQ
					where PQ.Person_id = EvnPS.Person_id
					and PQ.PersonQuarantine_endDT is null
				) then 2 else 1 end as "PersonQuarantine_IsOn",
				
				to_char(EvnPS.EvnPS_OutcomeDT, 'DD.MM.YYYY HH24:MI') as "EvnPS_OutcomeDT",
				PS.Sex_id as "Sex_id",
				PReg.PersonRegister_id as "PersonRegister_id",
				RTRIM(COALESCE(SST.SocStatus_Name, '')) as "SocStatus_Name",
				CCC.CmpCallCard_EmgTeamComm as "CmpCallCard_EmgTeamComm"
			from v_EvnPS EvnPS 
				inner join lateral (select * from v_Person_all PS where EvnPS.Person_id = PS.Person_id and EvnPS.PersonEvn_id = PS.PersonEvn_id and EvnPS.Server_id = PS.Server_id limit 1) as PS on true
				left join v_SocStatus SST on SST.SocStatus_id = PS.SocStatus_id
				left join v_EvnDirection_all ED  on ED.EvnDirection_id = EvnPS.EvnDirection_id
				left join v_CmpCallCard CCC on CCC.CmpCallCard_id = EvnPS.CmpCallCard_id
				left join v_DirType DT  on ED.DirType_id = DT.DirType_id
				left join v_LpuSectionProfile LSP  on ED.LpuSectionProfile_id = LSP.LpuSectionProfile_id
				left join lateral(
					select *
					from v_Diag DiagD
					where ED.Diag_id = DiagD.Diag_id
					limit 1
				) DiagD on true
				left join v_LpuSection LS  on EvnPS.LpuSection_eid = LS.LpuSection_id
				left join lateral(
					select *
					from v_Diag Diag
					where EvnPS.Diag_pid = Diag.Diag_id
					limit 1
				) Diag on true
				left join lateral (
					select
						PersonRegister_id,
						PersonPregnancy_id
					from
						v_PersonPregnancy
					where Person_id = PS.Person_id
					ORDER BY PersonPregnancy_id DESC
					limit 1
				) PReg on true
				left join v_PrehospStatus EST  on EvnPS.PrehospStatus_id = EST.PrehospStatus_id
				--left join v_TimetableStac_lite TTS  on EvnPS.EvnPS_id = TTS.Evn_id
				LEFT JOIN LATERAL (
					Select TimetableStac_setDate, TimeTableStac_id from v_TimetableStac_lite TTS  where EvnPS.EvnPS_id = TTS.Evn_id or EvnPS.EvnDirection_id = TTS.EvnDirection_id limit 1
				) TTS ON true
				left join pmUserCache puc  on EvnPS.pmUser_updID = puc.pmUser_id
				LEFT JOIN LATERAL (
					select
						ES.EvnSection_id as ChildEvn_id,
						ES.EvnSection_setDate
					from
						v_EvnSection ES 
					where
						ES.EvnSection_pid = EvnPS.EvnPS_id
						and COALESCE(ES.EvnSection_IsPriem, 1) = 1
					limit 1
				) Child ON true
				left join lateral (
					select
						ES.EvnSection_id
					from
						v_EvnSection ES
					where
						ES.EvnSection_pid = EvnPS.EvnPS_id
					limit 1
				) EvnSection ON true
				
				--left join v_EvnLink EL  on EL.Evn_lid = EvnPS.EvnPS_id
				--left join v_EvnPL EPL  on EPL.EvnPL_id = EL.Evn_id
				LEFT JOIN LATERAL (
					Select EvnPL_id, EvnPL_NumCard from v_EvnLink EL  
					left join v_EvnPL EPL  on EPL.EvnPL_id = EL.Evn_id
					where EL.Evn_lid = EvnPS.EvnPS_id
					limit 1
				) EPL ON true
				left join v_PrehospArrive PA  on PA.PrehospArrive_id = EvnPS.PrehospArrive_id
				left join v_PrehospType PT  on PT.PrehospType_id = EvnPS.PrehospType_id
				left join lateral (
					select PersonLpuInfo_IsAgree
					from v_PersonLpuInfo
					where Lpu_id = EvnPS.Lpu_id
						and Person_id = EvnPS.Person_id
					order by PersonLpuInfo_id desc
					limit 1
				) as PLI on true
				left join v_LpuSection TTSLSd on EvnPS.LpuSection_did = TTSLSd.LpuSection_id
				left join v_Lpu LPUd on EvnPS.Lpu_did = LPUd.Lpu_id
				left join v_Org ORGd on ORGd.Org_id = EvnPS.Org_did
				
				
			where
				EvnPS.Lpu_id = (select LpuId from vars)
				AND EvnPS.LpuSection_pid = '34861'
				AND EvnPS.EvnPS_setDate between (select dt from mv)-interval '2 days' and (select dt from mv)
				and COALESCE(cast(EvnPS.EvnPS_OutcomeDT as date),(select dt from mv))>=(select dt from mv)
				/*AND ((
					--со статусом Находится в приемном - история болезни создана установленным днем и дата исхода пустая или позже
					-- #57215
					EvnPS.EvnPS_setDate <= (select dt from mv) and datediff('day', EvnPS.EvnPS_setDate, (select dt from mv)) < 3 and coalesce(cast(EvnPS.EvnPS_OutcomeDT as date), Child.EvnSection_setDate, ((select dt from mv) + interval '1 day')) > (select dt from mv)
				)
				OR (
					--со статусом Отказ на установленную дату или со статусом Госпитализирован на установленную дату
					(cast(EvnPS.EvnPS_OutcomeDT as date) = (select dt from mv) AND COALESCE(EvnPS.PrehospWaifRefuseCause_id,  EvnPS.LpuSection_eid) IS NOT NULL)
				)
				OR (
					--со статусом Госпитализирован на установленную дату
					(cast(EvnPS.EvnPS_OutcomeDT as date) = -date AND EvnPS.LpuSection_eid IS NOT NULL)
				)
				)*/
				
				
				

			order by
				"sortDate" DESC
		
