
            -- TOP SL, FIXDATE 13.01.2023, JIRA PROMEDWEB-137973

            with curDT as (select localtimestamp as curDate),
                curD as (select cast(localtimestamp AS date) as curDate)
            select
                accessType as "accessType",
                Lpu_id as "Lpu_id",
                Diag_id as "Diag_id",
                DiagSetPhaseId as "DiagSetPhaseId",
                DiagSetPhaseName as "DiagSetPhaseName",
                DiagSetPhase_aid as "DiagSetPhase_aid",
                DiagPhaseDescr as "DiagPhaseDescr",
                isPriem as "isPriem",
                Diag_pid as "Diag_pid",
                DiagRRS as "DiagRRS",
                IsRecoveryPotential as "IsRecoveryPotential",
                IsRecoveryPotentialName as "IsRecoveryPotentialName",
                EvnPS_NumCard as "EvnPS_NumCard",
                EvnPS_id as "EvnPS_id",
                EvnSection_id as "EvnSection_id",
                EvnSection_pid as "EvnSection_pid",
                EvnClass_id as "EvnClass_id",
                EvnDiagPS_class as "EvnDiagPS_class",
                Person_id as "Person_id",
                PersonEvn_id as "PersonEvn_id",
                Server_id as "Server_id",
                PersonLpuInfo_IsAgree as "PersonLpuInfo_IsAgree",
                Person_Age as "Person_Age",
                Sex_SysNick as "Sex_SysNick",
                LpuSection_Name as "LpuSection_Name",
                LowLpuSection_Name as "LowLpuSection_Name",
                MedPersonal_Fio as "MedPersonal_Fio",
                EvnSection_setDate as "EvnSection_setDate",
                EvnSection_setTime as "EvnSection_setTime",
                EvnSection_disDate as "EvnSection_disDate",
                EvnSection_disTime as "EvnSection_disTime",
                PayType_Name as "PayType_Name",
                PayTypeERSB_id as "PayTypeERSB_id",
                PayTypeERSB_Name as "PayTypeERSB_Name",
                LpuSectionWard_Name as "LpuSectionWard_Name",
                TariffClass_Name as "TariffClass_Name",
                LpuSection_id as "LpuSection_id",
                MedPersonal_id as "MedPersonal_id",
                LpuSectionWard_id as "LpuSectionWard_id",
                MedStaffFact_id as "MedStaffFact_id",
                MedSpecOms_id as "MedSpecOms_id",
                FedMedSpec_id as "FedMedSpec_id",
                Mes_id as "Mes_id",
                LpuSectionTransType_id as "LpuSectionTransType_id",
                PayType_id as "PayType_id",
                PayType_SysNick as "PayType_SysNick",
                TariffClass_id as "TariffClass_id",
                Diag_Name as "Diag_Name",
                Diag_Code as "Diag_Code",
                DeseaseType_id as "DeseaseType_id",
                DeseaseType_Name as "DeseaseType_Name",
                TumorStage_Name as "TumorStage_Name",
                PainIntensity_Name as "PainIntensity_Name",
                LeaveType_id as "LeaveType_id",
                LeaveType_Code as "LeaveType_Code",
                LeaveType_SysNick as "LeaveType_SysNick",
                LeaveType_Name as "LeaveType_Name",
                EvnSection_leaveDate as "EvnSection_leaveDate",
                EvnSection_leaveTime as "EvnSection_leaveTime",
                Leave_EvnClass_SysNick as "Leave_EvnClass_SysNick",
                Leave_id as "Leave_id",
                LeaveCause_id as "LeaveCause_id",
                ResultDesease_id as "ResultDesease_id",
                EvnLeave_UKL as "EvnLeave_UKL",
                IsSigned as "IsSigned",
                LeaveCause_Name as "LeaveCause_Name",
                ResultDesease_Name as "ResultDesease_Name",
                EvnLeave_IsAmbul as "EvnLeave_IsAmbul",
                Lpu_l_Name as "Lpu_l_Name",
                MedPersonal_d_Fin as "MedPersonal_d_Fin",
                EvnDie_IsWait as "EvnDie_IsWait",
                EvnDie_IsAnatom as "EvnDie_IsAnatom",
                EvnDie_expDate as "EvnDie_expDate",
                EvnDie_expTime as "EvnDie_expTime",
                EvnDie_locName as "EvnDie_locName",
                MedPersonal_a_Fin as "MedPersonal_a_Fin",
                Diag_a_Code as "Diag_a_Code",
                Diag_a_Name as "Diag_a_Name",
                LpuUnitType_o_Name as "LpuUnitType_o_Name",
                LpuSection_o_Name as "LpuSection_o_Name",
                LpuSectionProfile_id as "LpuSectionProfile_id",
                LpuUnitType_Code as "LpuUnitType_Code",
                LpuUnitType_id as "LpuUnitType_id",
                LpuUnitType_SysNick as "LpuUnitType_SysNick",
                EvnPS_HospCount as "EvnPS_HospCount",
                EvnPS_TimeDesease as "EvnPS_TimeDesease",
                EvnPS_IsNeglectedCase as "EvnPS_IsNeglectedCase",
                PrehospToxic_Name as "PrehospToxic_Name",
                PrehospTrauma_Name as "PrehospTrauma_Name",
                EvnPS_IsUnlaw as "EvnPS_IsUnlaw",
                EvnPS_IsUnport as "EvnPS_IsUnport",
                PrehospWaifRefuseCause_Name as "PrehospWaifRefuseCause_Name",
                PrehospWaifRefuseCause_id as "PrehospWaifRefuseCause_id",
                PrehospArrive_id as "PrehospArrive_id",
                PrehospArrive_SysNick as "PrehospArrive_SysNick",
                PrehospType_id as "PrehospType_id",
                PrehospType_SysNick as "PrehospType_SysNick",
                LpuSectionNEXT_id as "LpuSectionNEXT_id",
                EvnPS_IsTransfCall as "EvnPS_IsTransfCall",
                ResultClass_id as "ResultClass_id",
                ResultDeseaseType_id as "ResultDeseaseType_id",
                EvnPS_OutcomeDate as "EvnPS_OutcomeDate",
                EvnPS_OutcomeTime as "EvnPS_OutcomeTime",
                Mes_Code as "Mes_Code",
                Mes_Name as "Mes_Name",
                MesOld_Num as "MesOld_Num",
                EvnSection_KoikoDni as "EvnSection_KoikoDni",
                Mes_KoikoDni as "Mes_KoikoDni",
                Procent_KoikoDni as "Procent_KoikoDni",
                EvnSection_IsSigned as "EvnSection_IsSigned",
                ins_Name as "ins_Name",
                sign_Name as "sign_Name",
                insDT as "insDT",
                signDT as "signDT",
                CureStandart_Count as "CureStandart_Count",
                DiagFedMes_FileName as "DiagFedMes_FileName",
                Duration as "Duration",
                LpuSectionBedProfile_id as "LpuSectionBedProfile_id",
                LpuSectionBedProfile_Name as "LpuSectionBedProfile_Name",
                EvnSection_KSG as "EvnSection_KSG",
                EvnSection_KSGName as "EvnSection_KSGName",
                EvnSection_KSGNameNum as "EvnSection_KSGNameNum",
                EvnSection_KSGCoeff as "EvnSection_KSGCoeff",
                EvnSection_KSGUslugaNumber as "EvnSection_KSGUslugaNumber",
                EvnSection_CoeffCTP as "EvnSection_CoeffCTP",
                DrugTherapyScheme_Code as "DrugTherapyScheme_Code",
                DrugTherapyScheme_Name as "DrugTherapyScheme_Name",
                RehabScale_id as "RehabScale_id",
                RehabScale_Name as "RehabScale_Name",
                RehabScale_vid as "RehabScale_vid",
                RehabScaleOut_Name as "RehabScaleOut_Name",
                EvnSection_SofaScalePoints as "EvnSection_SofaScalePoints",
                MesRid_Code as "MesRid_Code",
                Mes_rid as "Mes_rid",
                EvnSection_KPG as "EvnSection_KPG",
                UslugaComplex_id as "UslugaComplex_id",
                Mes_sid as "Mes_sid",
                EvnSection_insideNumCard as "EvnSection_insideNumCard",
                es_LpuSectionProfile_id as "es_LpuSectionProfile_id",
                LpuSectionProfile_Code as "LpuSectionProfile_Code",
                LpuSectionProfile_Name as "LpuSectionProfile_Name",
                UslugaComplex_Code as "UslugaComplex_Code",
                UslugaComplex_Name as "UslugaComplex_Name",
                HTMedicalCareClass_id as "HTMedicalCareClass_id",
                isAllowFedResultFields as "isAllowFedResultFields",
                EvnSection_setDateYmd as "EvnSection_setDateYmd",
                LeaveType_prmid as "LeaveType_prmid",
                CmpCallCard_id as "CmpCallCard_id",
                LeaveType_fedid as "LeaveType_fedid",
                ResultDeseaseType_fedid as "ResultDeseaseType_fedid",
                PrmLeaveType_Code as "PrmLeaveType_Code",
                PrmLeaveType_Name as "PrmLeaveType_Name",
                FedLeaveType_Code as "FedLeaveType_Code",
                FedLeaveType_Name as "FedLeaveType_Name",
                FedResultDeseaseType_Code as "FedResultDeseaseType_Code",
                FedResultDeseaseType_Name as "FedResultDeseaseType_Name",
                EvnSection_IsPriem as "EvnSection_IsPriem",
                CureResult_id as "CureResult_id",
                CureResult_Name as "CureResult_Name",
                EvnSection_IsTerm as "EvnSection_IsTerm",
                RankinScale_id as "RankinScale_id",
                RankinScale_sid as "RankinScale_sid",
                RankinScale_Name as "RankinScale_Name",
                RankinScale_sName as "RankinScale_sName",
                EvnSection_InsultScale as "EvnSection_InsultScale",
                EvnSection_NIHSSAfterTLT as "EvnSection_NIHSSAfterTLT",
                EvnSection_NIHSSLeave as "EvnSection_NIHSSLeave",
                DiagFinance_IsRankin as "DiagFinance_IsRankin",
                ResultClass_Name as "ResultClass_Name",
                ResultDeseaseType_Name as "ResultDeseaseType_Name",
                EvnSection_IsST as "EvnSection_IsST",
                EvnSection_IsCardShock as "EvnSection_IsCardShock",
                EvnSection_StartPainHour as "EvnSection_StartPainHour",
                EvnSection_StartPainMin as "EvnSection_StartPainMin",
                EvnSection_GraceScalePoints as "EvnSection_GraceScalePoints",
                EvnSection_BarthelIdx as "EvnSection_BarthelIdx",
                
                PregnancyEvnPS_Period as "PregnancyEvnPS_Period",
                CovidType_id as "CovidType_id",
                RepositoryObserv_SpO2 as "RepositoryObserv_SpO2",
                PersonHeight_Height as "PersonHeight_Height",
                PersonWeight_Weight as "PersonWeight_Weight",
                PersonVitalParam_DiastolPress as "PersonVitalParam_DiastolPress",
                PersonVitalParam_SistolPress as "PersonVitalParam_SistolPress",
                PersonVitalParam_Temperature as "PersonVitalParam_Temperature",
                PersonVitalParam_BreathFrequency as "PersonVitalParam_BreathFrequency",
                PersonVitalParam_Pulse as "PersonVitalParam_Pulse",
                PersonVitalParam_HeartFrequency as "PersonVitalParam_HeartFrequency",
                RoutingLevel_id as "RoutingLevel_id",
                BirthSpecStac_id as "BirthSpecStac_id",
                EvnNotifyKas_id as "EvnNotifyKas_id"
            from (
                
                select
                    case when EvnPS.Lpu_id = '150441' then 'edit' else 'view' end as accessType,
                    EvnPS.Lpu_id,
                    Diag.Diag_id,
                    dsp.DiagSetPhase_id as DiagSetPhaseId,
                    dsp.DiagSetPhase_Name as DiagSetPhaseName,
                    EvnPS.DiagSetPhase_aid as DiagSetPhase_aid,
                    coalesce(esp.EvnSection_PhaseDescr, EvnPS.EvnPS_PhaseDescr_pid) as DiagPhaseDescr,
                    2 as isPriem,
                    Diag.Diag_pid,
                    null as DiagRRS,
                    
                null as IsRecoveryPotential,
                null as IsRecoveryPotentialName,
            
                    EvnPS.EvnPS_NumCard,
                    EvnPS.EvnPS_id,
                    EvnPS.CmpCallCard_id,
                    EvnPS.EvnPS_id as EvnSection_id,
                    EvnPS.EvnPS_id as EvnSection_pid,
                    EvnPS.EvnClass_id,
                    'EvnDiagPSRecep' as EvnDiagPS_class,
                    EvnPS.Person_id,
                    EvnPS.PersonEvn_id,
                    EvnPS.Server_id,
                    case
                        when persConsent.Consent_id is not null
                        then plia.PersonLpuInfo_IsAgree
                        else null
                    end as PersonLpuInfo_IsAgree,
                    dbo.Age2(PS.Person_BirthDay, EvnPS.EvnPS_setDate) as Person_Age,
                    Sex.Sex_SysNick,
                    RTRIM(coalesce(LS.LpuSection_Name, '')) as LpuSection_Name,
                    LOWER(RTRIM(coalesce(LS.LpuSection_Name, ''))) as LowLpuSection_Name,
                    coalesce(MP.Person_Fio,'') as MedPersonal_Fio,
                    to_char(EvnPS.EvnPS_setDate, 'dd.mm.yyyy') as EvnSection_setDate,
                    to_char(EvnPS.EvnPS_setTime, 'hh24:mi') as EvnSection_setTime,
                    '' as EvnSection_disDate,
                    null::varchar as EvnSection_disTime,
                    RTRIM(coalesce(PT.PayType_Name, '')) as PayType_Name,
                    null as PayTypeERSB_id,
                    null as PayTypeERSB_Name,
                    RTRIM(coalesce(LSW.LpuSectionWard_Name, '')) as LpuSectionWard_Name,
                    null as TariffClass_Name,
                    EvnPS.LpuSection_pid as LpuSection_id,
                    EvnPS.MedPersonal_pid as MedPersonal_id,
                    EvnPS.LpuSectionWard_id as LpuSectionWard_id,
                    MSF.MedStaffFact_id as MedStaffFact_id,
                    MSF.MedSpecOms_id as MedSpecOms_id,
                    MSO.MedSpec_id as FedMedSpec_id,
                    null as Mes_id,
                    null as LpuSectionTransType_id,
                    EvnPS.PayType_id as PayType_id,
                    PT.PayType_SysNick,
                    null as TariffClass_id,
                    coalesce(Diag.Diag_Name, '') as Diag_Name,-- основной диагноз
                    coalesce(Diag.Diag_Code, '') as Diag_Code,
                    coalesce(DT.DeseaseType_id,0) as DeseaseType_id,
                    coalesce(DT.DeseaseType_Name, '') as DeseaseType_Name,
                    coalesce(TS.TumorStage_Name, '') as TumorStage_Name,
                    null as PainIntensity_Name,
                    case when ESNEXT.EvnSection_id is not null then -2 when EvnPS.PrehospWaifRefuseCause_id is not null then -1 else -3 end as LeaveType_id,
                    case when ESNEXT.EvnSection_id is not null then -2 when EvnPS.PrehospWaifRefuseCause_id is not null then -1 else -3 end as LeaveType_Code,
                    '' as LeaveType_SysNick,
                    '' as LeaveType_Name,
                    to_char(ESNEXT.EvnSection_setDate, 'dd.mm.yyyy') as EvnSection_leaveDate,
                    to_char(ESNEXT.EvnSection_setTime, 'hh24:mi') as EvnSection_leaveTime,
                    null as Leave_EvnClass_SysNick,
                    null as Leave_id,
                    null as LeaveCause_id,
                    null as ResultDesease_id,
                    null as EvnLeave_UKL,
                    null as IsSigned,
                    null as LeaveCause_Name,
                    null as ResultDesease_Name,
                    null as EvnLeave_IsAmbul,
                    null as Lpu_l_Name,-- перевод в <ЛПУ>
                    null as MedPersonal_d_Fin,
                    null as EvnDie_IsWait,
                    null as EvnDie_IsAnatom,
                    null as EvnDie_expDate,
                    null as EvnDie_expTime,
                    null as EvnDie_locName,
                    null as MedPersonal_a_Fin,
                    null as Diag_a_Code,
                    null as Diag_a_Name,
                    null as LpuUnitType_o_Name,
                    LSNEXT.LpuSection_Name as LpuSection_o_Name,
                    LSP.LpuSectionProfile_id,
                    LSBP.LpuSectionBedProfile_id,
                    LUT.LpuUnitType_Code,
                    LUT.LpuUnitType_id,
                    LUT.LpuUnitType_SysNick,
                    EvnPS.EvnPS_HospCount as EvnPS_HospCount,
                    EvnPS.EvnPS_TimeDesease as EvnPS_TimeDesease,
                    coalesce(IsNeglectedCase.YesNo_Name, '') as EvnPS_IsNeglectedCase,
                    PTX.PrehospToxic_Name as PrehospToxic_Name,
                    PTR.PrehospTrauma_Name as PrehospTrauma_Name,
                    coalesce(IsUnlaw.YesNo_Name, '') as EvnPS_IsUnlaw,
                    coalesce(IsUnport.YesNo_Name, '') as EvnPS_IsUnport,
                    PWRC.PrehospWaifRefuseCause_Name,
                    PWRC.PrehospWaifRefuseCause_id,
                    PHA.PrehospArrive_id,
                    PHA.PrehospArrive_SysNick,
                    PHT.PrehospType_id,
                    PHT.PrehospType_SysNick,
                    LSNEXT.LpuSection_id as LpuSectionNEXT_id,
                    EvnPS.EvnPS_IsTransfCall as EvnPS_IsTransfCall,
                    EvnPS.ResultClass_id,
                    EvnPS.ResultDeseaseType_id,
                    to_char(EvnPS.EvnPS_OutcomeDT, 'dd.mm.yyyy') as EvnPS_OutcomeDate,
                    to_char(EvnPS.EvnPS_OutcomeDT, 'HH24:MI') as EvnPS_OutcomeTime,
                    EvnPS.EvnPS_IsWithoutDirection,
                    null as Mes_Code,
                    null as Mes_Name,
                    null as MesOld_Num,
                    null as EvnSection_KoikoDni,
                    null as Mes_KoikoDni,
                    null as Procent_KoikoDni,
                    null as EvnSection_IsSigned,
                    null as ins_Name,
                    null as sign_Name,
                    null as insDT,
                    null as signDT,
                    FM.CureStandart_Count,
                    DFM.DiagFedMes_FileName,
                    null as Duration,
                    null as EvnSection_KSG,
                    null as EvnSection_KSGName,
                    null as EvnSection_KSGNameNum,
                    null as EvnSection_KSGCoeff,
                    null as EvnSection_KSGUslugaNumber,
                    null as EvnSection_CoeffCTP,
                    null as DrugTherapyScheme_Code,
                    null as DrugTherapyScheme_Name,
                    null as RehabScale_id,
                    null as RehabScale_Name,
                    null as RehabScale_vid,
                    null as RehabScaleOut_Name,
                    null as EvnSection_SofaScalePoints,
                    null as MesRid_Code,
                    null as Mes_rid,
                    null as EvnSection_KPG,
                    null as UslugaComplex_id,
                    null as Mes_sid,
                    null as EvnSection_insideNumCard,
                    null as es_LpuSectionProfile_id,
                    null as LpuSectionProfile_Code,
                    null as LpuSectionProfile_Name,
                    null as es_LpuSectionBedProfile_id,
                    null as LpuSectionBedProfile_Code,
                    null as LpuSectionBedProfile_Name,
                    null as UslugaComplex_Code,
                    null as UslugaComplex_Name,
                    null as HTMedicalCareClass_id,
                    0 as isAllowFedResultFields,
                    to_char(EvnPS.EvnPS_setDT, 'yyyy-mm-dd') as EvnSection_setDateYmd,
                    null as LeaveType_prmid,
                    null as LeaveType_fedid,
                    null as ResultDeseaseType_fedid,
                    null as PrmLeaveType_Code,
                    null as PrmLeaveType_Name,
                    null as FedLeaveType_Code,
                    null as FedLeaveType_Name,
                    null as FedResultDeseaseType_Code,
                    null as FedResultDeseaseType_Name,
                    2 as EvnSection_IsPriem,
                    null as CureResult_id,
                    null as CureResult_Name,
                    null as EvnSection_IsTerm,
                    null as RankinScale_id,
                    null as RankinScale_sid,
                    null as RankinScale_Name,
                    null as RankinScale_sName,
                    null as EvnSection_InsultScale,
                    null as EvnSection_NIHSSAfterTLT,
                    null as EvnSection_NIHSSLeave,
                    null as DiagFinance_IsRankin,
                    null as ResultClass_Name,
                    null as ResultDeseaseType_Name,
                    null as EvnSection_IsST,
                    null as EvnSection_IsCardShock,
                    null as EvnSection_StartPainHour,
                    null as EvnSection_StartPainMin,
                    null as EvnSection_GraceScalePoints,
                    null as EvnSection_BarthelIdx,
                    
                    PEPS.PregnancyEvnPS_Period,
                    RepositoryObserv.CovidType_id,
                    RepositoryObserv.RepositoryObserv_SpO2,
                    PH.PersonHeight_Height,
                    PW.PersonWeight_Weight,
                    PVP.PersonVitalParam_DiastolPress,
                    PVP.PersonVitalParam_SistolPress,
                    PVP.PersonVitalParam_Temperature,
                    PVP.PersonVitalParam_BreathFrequency,
                    PVP.PersonVitalParam_Pulse,
                    PVP.PersonVitalParam_HeartFrequency,
                    RoutingLevel.RoutingLevel_id,
                    null as BirthSpecStac_id,
                    null as EvnNotifyKas_id
                from v_EvnPS EvnPS
                    left join v_MedStaffFact UMSF on UMSF.MedStaffFact_id = '23356'
                    left join v_PersonState PS on EvnPS.Person_id = PS.Person_id
                    left join v_Sex Sex on Sex.Sex_id = PS.Sex_id
                    left join v_LpuSection LS on LS.LpuSection_id = EvnPS.LpuSection_pid
                    left join v_LpuUnit LU on LU.LpuUnit_id = LS.LpuUnit_id
                    left join v_LpuSectionProfile LSP on LSP.LpuSectionProfile_id = LS.LpuSectionProfile_id
                    left join v_LpuSectionBedProfile LSBP on LSBP.LpuSectionBedProfile_id = LS.LpuSectionBedProfile_id
                    left join v_LpuUnitType LUT on LUT.LpuUnitType_id = LU.LpuUnitType_id
                    left join v_PayType PT on PT.PayType_id = EvnPS.PayType_id
                    left join v_MedPersonal MP on MP.MedPersonal_id = EvnPS.MedPersonal_pid and MP.Lpu_id = EvnPS.Lpu_id
                    left join v_EvnSection esp
                        on esp.EvnSection_pid = EvnPS.EvnPS_id AND coalesce(esp.EvnSection_IsPriem, 1) = 2
                    LEFT JOIN LATERAL (
                        select PH.PersonHeight_Height
                        from v_PersonHeight PH
                        where PH.Evn_id = EvnPS.EvnPS_id
                        order by PersonHeight_insDT DESC limit 1 ) PH on true

                    LEFT JOIN LATERAL (
                            select Pw.PersonWeight_Weight
                            from v_PersonWeight Pw
                            where Pw.Evn_id = EvnPS.EvnPS_id
                            order by Pw.PersonWeight_insDT DESC limit 1 ) PW on true

                    LEFT JOIN LATERAL (
                        select *
                        from v_PersonVitalParam pvp
                        where PVP.Evn_id = EvnPS.EvnPS_id limit 1) PVP on true

                    left join lateral( select
                        MSF.MedStaffFact_id, MSF.MedSpecOms_id
                        from v_MedStaffFact MSF
                        where MSF.MedPersonal_id = EvnPS.MedPersonal_pid and MSF.LpuSection_id = EvnPS.LpuSection_pid
                        limit 1
                    ) MSF on true
                    left join v_MedSpecOms MSO on MSO.MedSpecOms_id = MSF.MedSpecOms_id
                    left join lateral (select * from v_Diag Diag where  Diag.Diag_id = EvnPS.Diag_pid limit 1) Diag on true
                    left join v_DiagSetPhase dsp
                        on dsp.DiagSetPhase_id = coalesce(esp.DiagSetPhase_id, EvnPS.DiagSetPhase_pid)
                    left join v_DeseaseType DT on DT.DeseaseType_id = EvnPS.DeseaseType_id
                    left join v_TumorStage TS on TS.TumorStage_id = EvnPS.TumorStage_id
                    
                    left join PrehospToxic PTX on PTX.PrehospToxic_id = EvnPS.PrehospToxic_id
                    left join v_PrehospTrauma PTR on PTR.PrehospTrauma_id = EvnPS.PrehospTrauma_id
                    left join v_PrehospWaifRefuseCause PWRC on PWRC.PrehospWaifRefuseCause_id = EvnPS.PrehospWaifRefuseCause_id
                    left join v_PrehospType PHT on PHT.PrehospType_id = EvnPS.PrehospType_id
                    left join v_PrehospArrive PHA on PHA.PrehospArrive_id = EvnPS.PrehospArrive_id
                    left join YesNo IsUnlaw on IsUnlaw.YesNo_id = EvnPS.EvnPS_IsUnlaw
                    left join YesNo IsUnport on IsUnport.YesNo_id = EvnPS.EvnPS_IsUnport
                    left join v_PregnancyEvnPS PEPS on PEPS.EvnPS_id = EvnPS.EvnPS_id
                    left join YesNo IsNeglectedCase on IsNeglectedCase.YesNo_id = EvnPS.EvnPS_IsNeglectedCase
                    left join LpuSectionWard LSW on LSW.LpuSectionWard_id = EvnPS.LpuSectionWard_id
                    -- если есть следующее движение то исход - перевод в другое отделение
                    left join v_EvnSection ESNEXT on ESNEXT.EvnSection_id = EvnPS.EvnSection_firstid
                        and ESNEXT.EvnSection_pid = EvnPS.EvnPS_id
                    
                    left join LpuSection LSNEXT on LSNEXT.LpuSection_id = ESNEXT.LpuSection_id
                    -- для гиперссылки на МЭС на коде диагноза
                    left join lateral(
                        
        select
            COUNT(cs.CureStandart_id) as CureStandart_Count
        from v_CureStandartDiag csd
            inner join v_CureStandart cs on csd.CureStandart_id = cs.CureStandart_id
        where
            (csd.Diag_id = Diag.Diag_pid or csd.Diag_id = Diag.Diag_id)
            and cs.CureStandartAgeGroupType_id in (case when dbo.Age2(PS.Person_BirthDay, EvnPS.EvnPS_setDT) < 18 then 2 else 1 end,3)
            and cast(cs.CureStandart_begDate as date) <= cast(EvnPS.EvnPS_setDT as date)
            and (cs.CureStandart_endDate is null or cast(cs.CureStandart_endDate as date) > cast(EvnPS.EvnPS_setDT as date))
        
                    ) FM on true
                    left join lateral(
                        
                select null as DiagFedMes_FileName
            
                    ) DFM on true
                    left join lateral(
                        select
                            t1.CovidType_id,
                            t1.RepositoryObserv_SpO2
                        from
                            v_RepositoryObserv t1
                        where
                            t1.Evn_id = EvnPS.EvnPS_id
                        limit 1
                    ) RepositoryObserv on true
                    left join lateral(
                        select
                            RM.RoutingLevel_id
                        from
                            v_RoutingMap RM
                            inner join v_RoutingProfile RP on RP.RoutingProfile_id = RM.RoutingProfile_id
                            and RoutingProfile_sysnick = 'oks'
                        where
                            RM.Lpu_id = EvnPS.Lpu_id
                            and RM.RoutingMap_endDate is null
                            and RP.RoutingProfile_endDate is null
                        order by
                            RM.RoutingLevel_id
                        limit 1
                    ) RoutingLevel on true
                    left join lateral (
                        select
                            plia.PersonLpuInfo_IsAgree
                        from v_PersonLpuInfo plia
                        where
                            plia.Lpu_id = EvnPS.Lpu_id
                            and plia.Person_id = EvnPS.Person_id
                        order by plia.PersonLpuInfo_id desc
                        limit 1
                    ) as plia on true
                    left join lateral (
                        select
                            con.Consent_id
                        from dbo.Consent con
                            left join dbo.ConsentType ct on con.ConsentType_id = ct.ConsentType_id
                        where
                            con.Consent_delDT is null
                            and con.Consent_begDT <= (select curDate from curDT)
                            and (con.Consent_endDT >= (select curDate from curDT) or con.Consent_endDT is null)
                            and con.Consent_isCancel = 1
                            and ct.ConsentType_SysNick = 'pers'
                            and con.Person_id = EvnPS.Person_id
                        limit 1
                    ) persConsent on true
                where
                    EvnPS.EvnPS_id = '190101011277411'
                union
                
                select
                    case when ES.Lpu_id = '150441' AND (ES.LpuSection_id = UMSF.LpuSection_id
                OR exists (
                    select WG.WorkGraph_id
                    from v_WorkGraph WG
                    where
                        WG.MedStaffFact_id = '23356'
                        and CAST(WG.WorkGraph_begDT as date) <= (select curDate from curD)
                        and CAST(WG.WorkGraph_endDT as date) >= (select curDate from curD)
                    limit 1
                    )
                or exists (
                    select 1
                      from dbo.EvnReanimatPeriod ERP
                     inner join v_MedServiceMedPersonal MSMP  on MSMP.MedService_id = ERP.MedService_id and UMSF.MedPersonal_id = MSMP.MedPersonal_id
                     where ERP.LpuSection_id = ES.LpuSection_id
                    limit 1
                    )
                )
             then 'edit' else 'view' end as accessType,
                    ES.Lpu_id,
                    Diag.Diag_id,
                    coalesce(dsp.DiagSetPhase_id, dspeps.DiagSetPhase_id) as DiagSetPhaseId,
                    coalesce(dsp.DiagSetPhase_Name, dspeps.DiagSetPhase_Name) as DiagSetPhaseName,
                    EvnPS.DiagSetPhase_aid as DiagSetPhase_aid,
                    coalesce(ES.EvnSection_PhaseDescr, EvnPS.EvnPS_PhaseDescr_pid) as DiagPhaseDescr,
                    coalesce(ES.EvnSection_isPriem, 1) as isPriem,
                    Diag.Diag_pid,
                    null as DiagRRS,
                    
                null as IsRecoveryPotential,
                null as IsRecoveryPotentialName,
            
                    EvnPS.EvnPS_NumCard,
                    EvnPS.EvnPS_id,
                    EvnPS.CmpCallCard_id,
                    ES.EvnSection_id,
                    ES.EvnSection_pid,
                    ES.EvnClass_id,
                    'EvnDiagPSSect' as EvnDiagPS_class,
                    ES.Person_id,
                    ES.PersonEvn_id,
                    ES.Server_id,
                    case
                        when persConsent.Consent_id is not null
                        then plia.PersonLpuInfo_IsAgree
                        else null
                    end as PersonLpuInfo_IsAgree,
                    dbo.Age2(PS.Person_BirthDay, ES.EvnSection_setDate) as Person_Age,
                    Sex.Sex_SysNick,
                    RTRIM(coalesce(LS.LpuSection_Name, '')) as LpuSection_Name,
                    LOWER(RTRIM(coalesce(LS.LpuSection_Name, ''))) as LowLpuSection_Name,
                    coalesce(MP.Person_Fio,'') as MedPersonal_Fio,
                    to_char(ES.EvnSection_setDate, 'dd.mm.yyyy') as EvnSection_setDate,
                    to_char(ES.EvnSection_setTime, 'hh24:mi') as EvnSection_setTime,
                    to_char(ES.EvnSection_disDate, 'dd.mm.yyyy') as EvnSection_disDate,
                    to_char(ES.EvnSection_disTime, 'hh24:mi') as EvnSection_disTime,
                    RTRIM(coalesce(PT.PayType_Name, '')) as PayType_Name,
                    PTE.PayTypeERSB_id,
                    RTRIM(coalesce(PTE.PayTypeERSB_Name, '')) as PayTypeERSB_Name,
                    RTRIM(coalesce(LSW.LpuSectionWard_Name, '')) as LpuSectionWard_Name,
                    coalesce(TC.TariffClass_Name,'') as TariffClass_Name,
                    ES.LpuSection_id as LpuSection_id,
                    ES.MedPersonal_id as MedPersonal_id,
                    ES.LpuSectionWard_id as LpuSectionWard_id,
                    MSF.MedStaffFact_id as MedStaffFact_id,
                    MSF.MedSpecOms_id as MedSpecOms_id,
                    MSO.MedSpec_id as FedMedSpec_id,
                    ES.Mes_id as Mes_id,
                    ES.LpuSectionTransType_id,
                    ES.PayType_id as PayType_id,
                    PT.PayType_SysNick,
                    ES.TariffClass_id as TariffClass_id,
                    coalesce(Diag.Diag_Name, '') as Diag_Name,-- основной диагноз
                    coalesce(Diag.Diag_Code, '') as Diag_Code,
                    coalesce(DT.DeseaseType_id,0) as DeseaseType_id,
                    coalesce(DT.DeseaseType_Name, '') as DeseaseType_Name,
                    coalesce(TS.TumorStage_Name, '') as TumorStage_Name,
                    coalesce(PI.PainIntensity_Name, '') as PainIntensity_Name,
                    LT.LeaveType_id,
                    LT.LeaveType_Code,
                    LT.LeaveType_SysNick,
                    LT.LeaveType_Name,
                    to_char(ES.EvnSection_disDate, 'dd.mm.yyyy') as EvnSection_leaveDate,
                    to_char(ES.EvnSection_disTime, 'hh24:mi') as EvnSection_leaveTime,
                    null as Leave_EvnClass_SysNick,
                    null as Leave_id,
                    null as LeaveCause_id,
                    null as ResultDesease_id,
                    null as EvnLeave_UKL,
                    null as IsSigned,
                    null as LeaveCause_Name,
                    null as ResultDesease_Name,
                    null as EvnLeave_IsAmbul,
                    null as Lpu_l_Name,
                    null as MedPersonal_d_Fin,
                    null as EvnDie_IsWait,
                    null as EvnDie_IsAnatom,
                    null as EvnDie_expDate,
                    null as EvnDie_expTime,
                    null as EvnDie_locName,
                    null as MedPersonal_a_Fin,
                    null as Diag_a_Code,
                    null as Diag_a_Name,
                    null as LpuUnitType_o_Name,
                    LSNEXT.LpuSection_Name as LpuSection_o_Name,
                    LS.LpuSectionProfile_id,
                    LS.LpuSectionBedProfile_id,
                    LUT.LpuUnitType_Code,
                    LUT.LpuUnitType_id,
                    LUT.LpuUnitType_SysNick,
                    null as EvnPS_HospCount,
                    null as EvnPS_TimeDesease,
                    null as EvnPS_IsNeglectedCase,
                    null as PrehospToxic_Name,
                    null as PrehospTrauma_Name,
                    null as EvnPS_IsUnlaw,
                    null as EvnPS_IsUnport,
                    PWRC.PrehospWaifRefuseCause_Name,
                    PWRC.PrehospWaifRefuseCause_id,
                    PHA.PrehospArrive_id,
                    PHA.PrehospArrive_SysNick,
                    PHT.PrehospType_id,
                    PHT.PrehospType_SysNick,
                    LSNEXT.LpuSection_id as LpuSectionNEXT_id,
                    EvnPS.EvnPS_IsTransfCall as EvnPS_IsTransfCall,
                    EvnPS.ResultClass_id,
                    EvnPS.ResultDeseaseType_id,
                    to_char(EvnPS.EvnPS_OutcomeDT, 'dd.mm.yyyy') as EvnPS_OutcomeDate,
                    to_char(EvnPS.EvnPS_OutcomeDT, 'HH24:MI') as EvnPS_OutcomeTime,
                    EvnPS.EvnPS_IsWithoutDirection,
                    
                            Mes.Mes_Code as Mes_Code,
                            Mes.Mes_Name as Mes_Name,
                        
                    Mes.MesOld_Num as MesOld_Num,
                    case
                        when LUT.LpuUnitType_Code = 2 and date_part('day', coalesce(ES.EvnSection_disDate,(select curDate from curDT)) - ES.EvnSection_setDate) + 1 > 1
                        then date_part('day', coalesce(ES.EvnSection_disDate,(select curDate from curDT)) - ES.EvnSection_setDate)
                        else date_part('day', coalesce(ES.EvnSection_disDate,(select curDate from curDT)) - ES.EvnSection_setDate) + 1
                    end as EvnSection_KoikoDni,
                    Mes.Mes_KoikoDni as Mes_KoikoDni,
                    case when Mes.Mes_KoikoDni is not null and Mes.Mes_KoikoDni > 0
                        then
                            case
                                when LUT.LpuUnitType_Code = 2 and date_part('day', coalesce(ES.EvnSection_disDate,(select curDate from curDT)) - ES.EvnSection_setDate) + 1 > 1
                                then CAST((date_part('day', coalesce(ES.EvnSection_disDate,(select curDate from curDT)) - ES.EvnSection_setDate))*100/Mes.Mes_KoikoDni AS decimal (8,2))
                                else CAST((date_part('day', coalesce(ES.EvnSection_disDate,(select curDate from curDT)) - ES.EvnSection_setDate) + 1)*100/Mes.Mes_KoikoDni AS decimal (8,2))
                            end
                        else null
                    end as Procent_KoikoDni,
                    ES.EvnSection_IsSigned,
                    rtrim(coalesce(pucins.PMUser_surName,pucins.PMUser_Name,'')) ||' '|| rtrim(coalesce(pucins.PMUser_firName,'')) ||' '|| rtrim(coalesce(pucins.PMUser_secName,'')) as ins_Name,
                    rtrim(coalesce(pucsign.PMUser_surName,pucsign.PMUser_Name,'')) ||' '|| rtrim(coalesce(pucsign.PMUser_firName,'')) ||' '|| rtrim(coalesce(pucsign.PMUser_secName,'')) as sign_Name,
                    to_char(ES.EvnSection_insDT, 'dd.mm.yyyy HH24:MI') as insDT,
                    to_char(ES.EvnSection_signDT, 'dd.mm.yyyy HH24:MI') as signDT,
                    FM.CureStandart_Count,
                    DFM.DiagFedMes_FileName
                    ,null as Duration,
                    case when mtmes.MesType_id <> 4 then mtmes.Mes_Code else '' end as EvnSection_KSG,
                    case when mtmes.MesType_id <> 4 then mtmes.Mes_Code || coalesce('. ' || mtmes.Mes_Name,'') else '' end as EvnSection_KSGName,
                    case when mtmes.MesType_id <> 4 then mtmes.Mes_Code || coalesce('. ' || mtmes.MesOld_Num, '') || coalesce('. ' || mtmes.Mes_Name, '') else '' end as EvnSection_KSGNameNum,
                    cast(mt.MesTariff_Value as numeric(16, 2)) as EvnSection_KSGCoeff
                    ,null as EvnSection_KSGUslugaNumber,
                    ES.EvnSection_CoeffCTP,
                    DTS.DrugTherapyScheme_Code,
                    DTS.DrugTherapyScheme_Name,
                    RSC.RehabScale_id,
                    RSC.RehabScale_Name,
                    RSCOut.RehabScale_id as RehabScale_vid,
                    RSCOut.RehabScale_Name as RehabScaleOut_Name,
                    es.EvnSection_SofaScalePoints,
                    mtmes.Mes_Code as MesRid_Code,
                    mtmes.Mes_id as Mes_rid,
                    KPG.Mes_Code as EvnSection_KPG,
                    ES.UslugaComplex_id,
                    ES.Mes_sid,
                    ES.EvnSection_insideNumCard,
                    ES.LpuSectionProfile_id as es_LpuSectionProfile_id,
                    LSP.LpuSectionProfile_Code,
                    LSP.LpuSectionProfile_Name,
                    ES.LpuSectionBedProfile_id as es_LpuSectionBedProfile_id,
                    LSBP.LpuSectionBedProfile_Code,
                    LSBP.LpuSectionBedProfile_Name,
                    UC.UslugaComplex_Code,
                    UC.UslugaComplex_Name,
                    ES.HTMedicalCareClass_id,
                    0 as isAllowFedResultFields,
                    to_char(coalesce(ES.EvnSection_setDT, EvnPS.EvnPS_setDT), 'yyyy-mm-dd') as EvnSection_setDateYmd,
                    ES.LeaveType_prmid,
                    ES.LeaveType_fedid,
                    ES.ResultDeseaseType_fedid,
                    prmLT.LeaveType_Code as PrmLeaveType_Code,
                    prmLT.LeaveType_Name as PrmLeaveType_Name,
                    fedLT.LeaveType_Code as FedLeaveType_Code,
                    fedLT.LeaveType_Name as FedLeaveType_Name,
                    fedRDT.ResultDeseaseType_Code as FedResultDeseaseType_Code,
                    fedRDT.ResultDeseaseType_Name as FedResultDeseaseType_Name,
                    coalesce(ES.EvnSection_IsPriem,1) as EvnSection_IsPriem,
                    ES.CureResult_id,
                    CR.CureResult_Name,
                    ES.EvnSection_IsTerm,
                    RS.RankinScale_id,
                    RS2.RankinScale_id as RankinScale_sid,
                    RS.RankinScale_Name,
                    RS2.RankinScale_Name as RankinScale_sName,
                    ES.EvnSection_InsultScale,
                    ES.EvnSection_NIHSSAfterTLT,
                    ES.EvnSection_NIHSSLeave,
                    coalesce(DiagF.DiagFinance_IsRankin, 1) as DiagFinance_IsRankin,
                    RC.ResultClass_Name,
                    RDT.ResultDeseaseType_Name,
                    IsST.YesNo_Name as EvnSection_IsST,
                    IsCardShock.YesNo_Name as EvnSection_IsCardShock,
                    ES.EvnSection_StartPainHour,
                    ES.EvnSection_StartPainMin,
                    ES.EvnSection_GraceScalePoints,
                    ES.EvnSection_BarthelIdx,
                    
                    PEPS.PregnancyEvnPS_Period,
                    RepositoryObserv.CovidType_id,
                    RepositoryObserv.RepositoryObserv_SpO2,
                    PH.PersonHeight_Height,
                    PW.PersonWeight_Weight,
                    PVP.PersonVitalParam_DiastolPress,
                    PVP.PersonVitalParam_SistolPress,
                    PVP.PersonVitalParam_Temperature,
                    PVP.PersonVitalParam_BreathFrequency,
                    PVP.PersonVitalParam_Pulse,
                    PVP.PersonVitalParam_HeartFrequency,
                    RoutingLevel.RoutingLevel_id,
                    coalesce(bss.BirthSpecStac_id, pnb.BirthSpecStac_id) as BirthSpecStac_id,
                    ENK.EvnNotifyKas_id
                from v_EvnSection ES
                    inner join v_EvnPS EvnPS on EvnPS.EvnPS_id = ES.EvnSection_pid
                    
                left join lateral (
                    select
                        UslugaComplex_id
                    from
                        v_MesUsluga
                    where
                        Mes_id = es.Mes_sid
                        and MesUslugaLinkType_id = 4
                        and coalesce(MesUsluga_begDT, es.EvnSection_setDate) <= es.EvnSection_setDate
                        and coalesce(MesUsluga_endDT, es.EvnSection_setDate) >= es.EvnSection_setDate
                    limit 1
                ) mu on true
                left join v_UslugaComplex UC on UC.UslugaComplex_id = mu.UslugaComplex_id
            
                    left join v_LpuSectionProfile LSP on LSP.LpuSectionProfile_id = ES.LpuSectionProfile_id
                    left join v_PersonState PS on ES.Person_id = PS.Person_id
                    left join v_Sex Sex on Sex.Sex_id = PS.Sex_id
                    left join v_pmUserCache pucins on ES.pmUser_insID = pucins.PMUser_id
                    left join v_pmUserCache pucsign on ES.pmUser_signID = pucsign.PMUser_id
                    left join v_MedStaffFact UMSF on UMSF.MedStaffFact_id = '23356'
                    left join LpuSection LS on LS.LpuSection_id = ES.LpuSection_id
                    left join v_LpuSectionBedProfile LSBP on LSBP.LpuSectionBedProfile_id = ES.LpuSectionBedProfile_id
                    left join LpuUnit LU on LU.LpuUnit_id = LS.LpuUnit_id
                        -- данное условие не нужно, расхождение может быть только на тестовой, поскольку данные изначально кривые - на рабочей все отлично
                        -- or LU.LpuUnit_id = (select LS1.LpuUnit_id from LpuSection LS1 where LS1.LpuSection_id = LS.LpuSection_pid limit 1)
                    left join LpuUnitType LUT on LUT.LpuUnitType_id = LU.LpuUnitType_id
                    left join v_MesOld Mes on Mes.Mes_id = ES.Mes_id
                    left join v_PayType PT on PT.PayType_id = ES.PayType_id
                    left join v_PayTypeERSB PTE on PTE.PayTypeERSB_id = ES.PayTypeERSB_id
                    left join v_LeaveType LT on LT.LeaveType_id = ES.LeaveType_id
                    left join LpuSectionWard LSW on LSW.LpuSectionWard_id = ES.LpuSectionWard_id
                    left join v_TariffClass TC on TC.TariffClass_id = ES.TariffClass_id
                    left join v_CureResult CR on CR.CureResult_id = ES.CureResult_id
                    left join v_MedPersonal MP on MP.MedPersonal_id =
                        case
                            when coalesce(ES.EvnSection_isPriem, 1) = 2
	                        then EvnPS.MedPersonal_pid
	                        else ES.MedPersonal_id
                        end
                    and MP.Lpu_id =
                        case
                            when coalesce(ES.EvnSection_isPriem, 1) = 2
                            then EvnPS.Lpu_id
                            else ES.Lpu_id
                        end
                    left join v_MedStaffFact MSF on MSF.MedStaffFact_id = ES.MedStaffFact_id
                    left join v_MedSpecOms MSO on MSO.MedSpecOms_id = MSF.MedSpecOms_id
                    left join lateral (select * from v_Diag Diag where  Diag.Diag_id = ES.Diag_id limit 1) Diag on true
                    left join v_DiagSetPhase dsp on dsp.DiagSetPhase_id = ES.DiagSetPhase_id
                    left join v_DiagSetPhase dspeps on dspeps.DiagSetPhase_id = EvnPS.DiagSetPhase_pid
                    left join v_DiagFinance DiagF on Diag.Diag_id = DiagF.Diag_id
                    left join v_DeseaseType DT on DT.DeseaseType_id = ES.DeseaseType_id
                    left join v_TumorStage TS on TS.TumorStage_id = ES.TumorStage_id
                    
                    
                    left join v_PainIntensity PI on PI.PainIntensity_id = ES.PainIntensity_id
                    

                    LEFT JOIN LATERAL (
                        select PH.PersonHeight_Height
                        from v_PersonHeight PH
                        where PH.Evn_id = EvnPS.EvnPS_id
                        order by PersonHeight_insDT DESC limit 1 ) PH on true

                    LEFT JOIN LATERAL (
                        select ENK.EvnNotifyKas_id
                        from v_EvnNotifyKas ENK
                        left join v_MorbusKas MK on MK.EvnNotifyKas_id = ENK.EvnNotifyKas_id
                        where (ES.EvnSection_pid = ENK.EvnNotifyKas_rid or ENK.EvnNotifyKas_pid = ES.EvnSection_id) and ENK.EvnStatus_id = 59
                        and ( (MK.MorbusKas_insDT <= (select curDate from curDT) or MK.MorbusKas_insDT IS NULL)
                        and (MK.MorbusKas_disDT >= (select curDate from curDT) or MK.MorbusKas_disDT IS NULL) )
                        order by EvnNotifyKas_setDt desc) ENK on true

                    LEFT JOIN LATERAL (
                            select Pw.PersonWeight_Weight
                            from v_PersonWeight Pw
                            where Pw.Evn_id = EvnPS.EvnPS_id
                            order by Pw.PersonWeight_insDT DESC limit 1 ) PW on true

                    LEFT JOIN LATERAL (
                        select *
                        from v_PersonVitalParam pvp
                        where PVP.Evn_id = EvnPS.EvnPS_id limit 1) PVP on true

                    left join v_PrehospWaifRefuseCause PWRC on PWRC.PrehospWaifRefuseCause_id = EvnPS.PrehospWaifRefuseCause_id
                    left join v_PrehospType PHT on PHT.PrehospType_id = EvnPS.PrehospType_id
                    left join v_PrehospArrive PHA on PHA.PrehospArrive_id = EvnPS.PrehospArrive_id
                    -- если есть следующее движение то исход - перевод в другое отделение
                    left join lateral (
                        select *
                        from v_EvnSection
                        where EvnSection_pid = ES.EvnSection_pid
                            and EvnSection_setDT > ES.EvnSection_setDT
                        order by EvnSection_setDT asc, EvnSection_IsPriem desc nulls last
                        limit 1
                    ) as ESNEXT on true
                    left join LpuSection LSNEXT on LSNEXT.LpuSection_id = ESNEXT.LpuSection_id
                    left join v_RankinScale RS on RS.RankinScale_id = ES.RankinScale_id
                    left join v_RankinScale RS2 on RS2.RankinScale_id = ES.RankinScale_sid
                    -- для гиперссылки на МЭС на коде диагноза
                    left join lateral(
                        
        select
            COUNT(cs.CureStandart_id) as CureStandart_Count
        from v_CureStandartDiag csd
            inner join v_CureStandart cs on csd.CureStandart_id = cs.CureStandart_id
        where
            (csd.Diag_id = Diag.Diag_pid or csd.Diag_id = Diag.Diag_id)
            and cs.CureStandartAgeGroupType_id in (case when dbo.Age2(PS.Person_BirthDay, ES.EvnSection_setDT) < 18 then 2 else 1 end,3)
            and cast(cs.CureStandart_begDate as date) <= cast(ES.EvnSection_setDT as date)
            and (cs.CureStandart_endDate is null or cast(cs.CureStandart_endDate as date) > cast(ES.EvnSection_setDT as date))
        
                    ) FM on true
                    left join lateral(
                        
                select null as DiagFedMes_FileName
            
                    ) DFM on true
                        
                    left join v_MesTariff mt on mt.MesTariff_id = es.MesTariff_id -- Коэффициент КСГ/КПГ
                    left join v_MesOld mtmes on mtmes.Mes_id = mt.Mes_id -- КСГ из коэффициента
                    left join v_MesOld KPG on kpg.Mes_id = ES.Mes_kid
                    left join v_LeaveType prmLT on prmLT.LeaveType_id = ES.LeaveType_prmid
                    left join fed.v_LeaveType fedLT on fedLT.LeaveType_id = ES.LeaveType_fedid
                    left join fed.v_ResultDeseaseType fedRDT on fedRDT.ResultDeseaseType_id = ES.ResultDeseaseType_fedid
                    left join v_ResultClass RC on RC.ResultClass_id = EvnPS.ResultClass_id
                    left join v_ResultDeseaseType RDT on RDT.ResultDeseaseType_id = EvnPS.ResultDeseaseType_id
                    left join v_YesNo IsST on IsST.YesNo_id = ES.EvnSection_IsST
                    left join v_YesNo IsCardShock on IsCardShock.YesNo_id = ES.EvnSection_IsCardShock
                    left join v_PregnancyEvnPS PEPS on PEPS.EvnPS_id = ES.EvnSection_pid
                    left join lateral(
                        select
                            ESDTS.DrugTherapyScheme_id
                        from
                            v_EvnSectionDrugTherapyScheme ESDTS
                        where
                            ESDTS.EvnSection_id = ES.EvnSection_id
                        limit 1
                    ) ESDTS on true
                    
                    left join v_DrugTherapyScheme DTS on DTS.DrugTherapyScheme_id = ESDTS.DrugTherapyScheme_id
                    left join v_RehabScale RSC on RSC.RehabScale_id = ES.RehabScale_id
                    left join v_RehabScale RSCOut on RSCOut.RehabScale_id = ES.RehabScale_vid
                    left join lateral(
                        select BirthSpecStac_id
                        from v_BirthSpecStac
                        where EvnSection_id = ES.EvnSection_id
                        limit 1
                    ) bss on true
                    left join lateral(
                        select BirthSpecStac_id
                        from v_PersonNewBorn
                        where Person_id = PS.Person_id
                        limit 1
                    ) pnb on true
                    left join lateral(
                        select
                            t1.CovidType_id,
                            t1.RepositoryObserv_SpO2
                        from
                            v_RepositoryObserv t1
                        where
                            t1.Evn_id = ES.EvnSection_pid
                        limit 1
                    ) RepositoryObserv on true
                    left join lateral(
                        select
                            RM.RoutingLevel_id
                        from
                            v_RoutingMap RM
                            inner join v_RoutingProfile RP on RP.RoutingProfile_id = RM.RoutingProfile_id
                            and RoutingProfile_sysnick = 'oks'
                        where
                            RM.Lpu_id = ES.Lpu_id
                            and RM.RoutingMap_endDate is null
                            and RP.RoutingProfile_endDate is null
                        order by
                            RM.RoutingLevel_id
                        limit 1
                    ) RoutingLevel on true
                    left join lateral (
                        select
                            plia.PersonLpuInfo_IsAgree
                        from v_PersonLpuInfo plia
                        where
                            plia.Lpu_id = ES.Lpu_id
                            and plia.Person_id = ES.Person_id
                        order by plia.PersonLpuInfo_id desc
                        limit 1
                    ) as plia on true
                    left join lateral (
                        select
                            con.Consent_id
                        from dbo.Consent con
                            left join dbo.ConsentType ct on con.ConsentType_id = ct.ConsentType_id
                        where
                            con.Consent_delDT is null
                            and con.Consent_begDT <= (select curDate from curDT)
                            and (con.Consent_endDT >= (select curDate from curDT) or con.Consent_endDT is null)
                            and con.Consent_isCancel = 1
                            and ct.ConsentType_SysNick = 'pers'
                            and con.Person_id = ES.Person_id
                        limit 1
                    ) persConsent on true
                where
                    ES.EvnSection_pid = '190101011277411' and coalesce(Diag.Diag_Code, '') not in('Z20.6','R75','Z21','Z83.0','O98.7','Z83.0','Z71.7') and coalesce(Diag.Diag_Code, '') not between 'F10.0' and 'F19.9' and coalesce(Diag.Diag_Code, '') not between 'F00.0' and 'F09' and coalesce(Diag.Diag_Code, '') not between 'F20.0' and 'F99' and coalesce(Diag.Diag_Code, '') not between 'B21.0' and 'B24' and coalesce(Diag.Diag_Code, '') not between 'B20.0' and 'B20.9' and coalesce(ES.Lpu_id, 0) not in(150417,150453)
            ) fr
            order by EvnSection_id
        
