
                
                
            with EvnPrescrFirst as(
                -- движения
                select
                    EP.PrescriptionType_id,
                    EP.Person_id,
                    EP.pmUser_insID,
                    EP.pmUser_updID,
                    EP.EvnPrescr_id,
                    EP.EvnPrescr_pid,
                    EP.EvnPrescr_rid,
                    coalesce(Regime.EvnPrescrRegime_didDT,Diet.EvnPrescrDiet_didDT,Obs.EvnPrescrObserv_didDT,EP.EvnPrescr_didDT) as EvnPrescr_didDT,
                    EP.PersonEvn_id,
                    EP.Server_id,
                    EP.Lpu_id,
                    EP.PrescrFailureType_id,
                    PFT.PrescrFailureType_Name,
                    EP.EvnPrescr_insDT,
                    EP.EvnPrescr_IsCito,
                    --EP.PrescriptionStatusType_id,
                    EP.EvnPrescr_Descr,
                    EP.EvnPrescr_setDT,
                    EP.EvnPrescr_setTime,
                    EP.EvnPrescr_IsExec,
                    coalesce(EPS.Diag_pid,ES.Diag_id) as Diag_id,
                    ES.EvnSection_id,
                    coalesce(EPS.LpuSectionWard_id, ES.LpuSectionWard_id) as LpuSectionWard_id,
                    coalesce(Regime.EvnPrescrRegime_IsExec,Diet.EvnPrescrDiet_IsExec,Obs.EvnPrescrObserv_IsExec,EP.EvnPrescr_IsExec,1) as EvnPrescrDay_IsExec,
                    coalesce(Regime.PrescriptionStatusType_id,Diet.PrescriptionStatusType_id,Obs.PrescriptionStatusType_id,EP.PrescriptionStatusType_id) as PrescriptionStatusType_id,
                    coalesce(Regime.EvnPrescrRegime_Descr,Diet.EvnPrescrDiet_Descr,Obs.EvnPrescrObserv_Descr,EP.EvnPrescr_Descr) as EvnPrescrDay_Descr,
                    coalesce(Regime.EvnPrescrRegime_setDT,Diet.EvnPrescrDiet_setDT,Obs.EvnPrescrObserv_setDT,EP.EvnPrescr_setDT) as EvnPrescrDay_setDT,
                    coalesce(Regime.EvnPrescrRegime_setTime,Diet.EvnPrescrDiet_setTime,Obs.EvnPrescrObserv_setTime,EP.EvnPrescr_setTime) as EvnPrescrDay_setTime,
                    coalesce(Regime.EvnPrescrRegime_id,Diet.EvnPrescrDiet_id,Obs.EvnPrescrObserv_id,EP.EvnPrescr_id) as EvnPrescrDay_id,
                    Regime.PrescriptionRegimeType_id,
                    Diet.PrescriptionDietType_id,
                    Obs.ObservTimeType_id,
                    Obs.pmUser_updID as userUPD,
                    EP.EvnCourse_id
                from v_EvnPrescr EP
                    left join v_PrescrFailureType PFT on EP.PrescrFailureType_id = PFT.PrescrFailureType_id
                    inner join v_EvnSection ES on ES.EvnSection_id = EP.EvnPrescr_pid
                    inner join Evn e on e.Evn_id = ES.EvnSection_pid -- КВС для фильтрации по датам
                    left join EvnPS EPS on 1=0 -- квс не нужна, но может использоваться в фильтрах
                    left join lateral(
                        SELECT -- по одному назначению вряд ли будет больше 500 наблюдений
                            EvnPrescrObserv_id, PrescriptionStatusType_id,
                            EvnPrescrObserv_Descr,
                            EvnPrescrObserv_setDT,
                            EvnPrescrObserv_didDT,
                            EvnPrescrObserv_setTime,
                            EvnPrescrObserv_IsExec,
                            ObservTimeType_id,
                            pmUser_updID
                        from v_EvnPrescrObserv EPO
                        WHERE
                            EP.PrescriptionType_id = 10
                            and EPO.Lpu_id = '13101850'
                            and EPO.EvnPrescrObserv_pid = EP.EvnPrescr_id
                            -- оказвыается может и больше 500 по одному назначению. Сделаем огрничения по дате, а то в выборку много ненужных записей попадает
                            and cast(EPO.EvnPrescrObserv_setDT as date) >= cast('2022-05-08' as date)
                            and cast(EPO.EvnPrescrObserv_setDT as date) <= cast('2022-05-08' as date)
                        limit 500
                    ) AS Obs on true
                     left join lateral(
                SELECT
                    EvnPrescrDiet_id, PrescriptionStatusType_id,
                    EvnPrescrDiet_Descr,
                    EvnPrescrDiet_setDT,
                    EvnPrescrDiet_didDT,
                    EvnPrescrDiet_setTime,
                    EvnPrescrDiet_IsExec,
                    PrescriptionDietType_id
                from v_EvnPrescrDiet EPD
                WHERE EP.PrescriptionType_id = 2
                and EPD.Lpu_id = '13101850'
                and EPD.EvnPrescrDiet_pid = EP.EvnPrescr_id
                limit 500
            ) Diet on true
            left join lateral (
                SELECT
                    EvnPrescrRegime_id, PrescriptionStatusType_id,
                    EvnPrescrRegime_Descr,
                    EvnPrescrRegime_setDT,
                    EvnPrescrRegime_didDT,
                    EvnPrescrRegime_setTime,
                    EvnPrescrRegime_IsExec,
                    PrescriptionRegimeType_id
                from v_EvnPrescrRegime WHERE EvnPrescrRegime_pid = EP.EvnPrescr_id
                limit 10000
            ) AS Regime ON true
                where EP.PrescriptionType_id != 4
                    and cast(E.Evn_setDT as date) <= cast('2022-05-08' as date) and coalesce(cast(E.Evn_disDT as date), cast('2022-05-08' as date)) >= cast('2022-05-08' as date)
                    and ES.LpuSection_id = '890101000000272'
                    and coalesce(ES.EvnSection_IsPriem, 1) = 1
                    and EP.Lpu_id = '13101850'
                     and ES.LeaveType_id is null

                union all

                -- КВС
                select
                    EP.PrescriptionType_id,
                    EP.Person_id,
                    EP.pmUser_insID,
                    EP.pmUser_updID,
                    EP.EvnPrescr_id,
                    EP.EvnPrescr_pid,
                    EP.EvnPrescr_rid,
                    coalesce(Regime.EvnPrescrRegime_didDT,Diet.EvnPrescrDiet_didDT,Obs.EvnPrescrObserv_didDT,EP.EvnPrescr_didDT) as EvnPrescr_didDT,
                    EP.PersonEvn_id,
                    EP.Server_id,
                    EP.Lpu_id,
                    EP.PrescrFailureType_id,
                    PFT.PrescrFailureType_Name,
                    EP.EvnPrescr_insDT,
                    EP.EvnPrescr_IsCito,
                    --EP.PrescriptionStatusType_id,
                    EP.EvnPrescr_Descr,
                    EP.EvnPrescr_setDT,
                    EP.EvnPrescr_setTime,
                    EP.EvnPrescr_IsExec,
                    coalesce(EPS.Diag_pid,ES.Diag_id) as Diag_id,
                    ES.Evn_id as EvnSection_id,
                    coalesce(EPS.LpuSectionWard_id, ES.LpuSectionWard_id) as LpuSectionWard_id,
                    coalesce(Regime.EvnPrescrRegime_IsExec,Diet.EvnPrescrDiet_IsExec,Obs.EvnPrescrObserv_IsExec,EP.EvnPrescr_IsExec,1) as EvnPrescrDay_IsExec,
                    coalesce(Regime.PrescriptionStatusType_id,Diet.PrescriptionStatusType_id,Obs.PrescriptionStatusType_id,EP.PrescriptionStatusType_id) as PrescriptionStatusType_id,
                    coalesce(Regime.EvnPrescrRegime_Descr,Diet.EvnPrescrDiet_Descr,Obs.EvnPrescrObserv_Descr,EP.EvnPrescr_Descr) as EvnPrescrDay_Descr,
                    coalesce(Regime.EvnPrescrRegime_setDT,Diet.EvnPrescrDiet_setDT,Obs.EvnPrescrObserv_setDT,EP.EvnPrescr_setDT) as EvnPrescrDay_setDT,
                    coalesce(Regime.EvnPrescrRegime_setTime,Diet.EvnPrescrDiet_setTime,Obs.EvnPrescrObserv_setTime,EP.EvnPrescr_setTime) as EvnPrescrDay_setTime,
                    coalesce(Regime.EvnPrescrRegime_id,Diet.EvnPrescrDiet_id,Obs.EvnPrescrObserv_id,EP.EvnPrescr_id) as EvnPrescrDay_id,
                    Regime.PrescriptionRegimeType_id,
                    Diet.PrescriptionDietType_id,
                    Obs.ObservTimeType_id,
                    Obs.pmUser_updID as userUPD,
                    EP.EvnCourse_id
                from v_EvnPrescr EP
                    left join v_PrescrFailureType PFT on EP.PrescrFailureType_id = PFT.PrescrFailureType_id
                    inner join EvnPS EPS on EPS.Evn_id = EP.EvnPrescr_pid
                    inner join Evn e on e.Evn_id = EPS.Evn_id -- КВС для фильтрации по датам
                    left join EvnSection ES on 1=0 -- движение не нужно, но может использоваться в фильтрах
                    left join lateral(
                        SELECT -- по одному назначению вряд ли будет больше 500 наблюдений
                            EvnPrescrObserv_id, PrescriptionStatusType_id,
                            EvnPrescrObserv_Descr,
                            EvnPrescrObserv_setDT,
                            EvnPrescrObserv_didDT,
                            EvnPrescrObserv_setTime,
                            EvnPrescrObserv_IsExec,
                            ObservTimeType_id,
                            pmUser_updID
                        from v_EvnPrescrObserv EPO
                        WHERE EP.PrescriptionType_id = 10
                            and EPO.Lpu_id = '13101850'
                            and EPO.EvnPrescrObserv_pid = EP.EvnPrescr_id
                            -- оказвыается может и больше 500 по одному назначению. Сделаем огрничения по дате.
                            and cast(EPO.EvnPrescrObserv_setDT as date) >= cast('2022-05-08' as date)
                            and cast(EPO.EvnPrescrObserv_setDT as date) <= cast('2022-05-08' as date)
                        limit 500
                    ) AS Obs on true
                     left join lateral(
                SELECT
                    EvnPrescrDiet_id, PrescriptionStatusType_id,
                    EvnPrescrDiet_Descr,
                    EvnPrescrDiet_setDT,
                    EvnPrescrDiet_didDT,
                    EvnPrescrDiet_setTime,
                    EvnPrescrDiet_IsExec,
                    PrescriptionDietType_id
                from v_EvnPrescrDiet EPD
                WHERE EP.PrescriptionType_id = 2
                and EPD.Lpu_id = '13101850'
                and EPD.EvnPrescrDiet_pid = EP.EvnPrescr_id
                limit 500
            ) Diet on true
            left join lateral (
                SELECT
                    EvnPrescrRegime_id, PrescriptionStatusType_id,
                    EvnPrescrRegime_Descr,
                    EvnPrescrRegime_setDT,
                    EvnPrescrRegime_didDT,
                    EvnPrescrRegime_setTime,
                    EvnPrescrRegime_IsExec,
                    PrescriptionRegimeType_id
                from v_EvnPrescrRegime WHERE EvnPrescrRegime_pid = EP.EvnPrescr_id
                limit 10000
            ) AS Regime ON true
                where EP.PrescriptionType_id != 4
                    and cast(E.Evn_setDT as date) <= cast('2022-05-08' as date) and coalesce(cast(E.Evn_disDT as date), cast('2022-05-08' as date)) >= cast('2022-05-08' as date)
                    and EPS.LpuSection_pid = '890101000000272'
                    and EP.Lpu_id = '13101850'
                     and ES.LeaveType_id is null

                union all

                -- назначения в приёмном (если они сохраняются на КВС)
                select
                    EP.PrescriptionType_id,
                    EP.Person_id,
                    EP.pmUser_insID,
                    EP.pmUser_updID,
                    EP.EvnPrescr_id,
                    EP.EvnPrescr_pid,
                    EP.EvnPrescr_rid,
                    coalesce(Regime.EvnPrescrRegime_didDT,Diet.EvnPrescrDiet_didDT,Obs.EvnPrescrObserv_didDT,EP.EvnPrescr_didDT) as EvnPrescr_didDT,
                    EP.PersonEvn_id,
                    EP.Server_id,
                    EP.Lpu_id,
                    EP.PrescrFailureType_id,
                    PFT.PrescrFailureType_Name,
                    EP.EvnPrescr_insDT,
                    EP.EvnPrescr_IsCito,
                    --EP.PrescriptionStatusType_id,
                    EP.EvnPrescr_Descr,
                    EP.EvnPrescr_setDT,
                    EP.EvnPrescr_setTime,
                    EP.EvnPrescr_IsExec,
                    ES.Diag_id,
                    ES.EvnSection_id,
                    ES.LpuSectionWard_id,
                    coalesce(Regime.EvnPrescrRegime_IsExec,Diet.EvnPrescrDiet_IsExec,Obs.EvnPrescrObserv_IsExec,EP.EvnPrescr_IsExec,1) as EvnPrescrDay_IsExec,
                    coalesce(Regime.PrescriptionStatusType_id,Diet.PrescriptionStatusType_id,Obs.PrescriptionStatusType_id,EP.PrescriptionStatusType_id) as PrescriptionStatusType_id,
                    coalesce(Regime.EvnPrescrRegime_Descr,Diet.EvnPrescrDiet_Descr,Obs.EvnPrescrObserv_Descr,EP.EvnPrescr_Descr) as EvnPrescrDay_Descr,
                    coalesce(Regime.EvnPrescrRegime_setDT,Diet.EvnPrescrDiet_setDT,Obs.EvnPrescrObserv_setDT,EP.EvnPrescr_setDT) as EvnPrescrDay_setDT,
                    coalesce(Regime.EvnPrescrRegime_setTime,Diet.EvnPrescrDiet_setTime,Obs.EvnPrescrObserv_setTime,EP.EvnPrescr_setTime) as EvnPrescrDay_setTime,
                    coalesce(Regime.EvnPrescrRegime_id,Diet.EvnPrescrDiet_id,Obs.EvnPrescrObserv_id,EP.EvnPrescr_id) as EvnPrescrDay_id,
                    Regime.PrescriptionRegimeType_id,
                    Diet.PrescriptionDietType_id,
                    Obs.ObservTimeType_id,
                    Obs.pmUser_updID as userUPD,
                    EP.EvnCourse_id
                from v_EvnPrescr EP
                    left join v_PrescrFailureType PFT on EP.PrescrFailureType_id = PFT.PrescrFailureType_id
                    inner join v_EvnSection ES on ES.EvnSection_pid = EP.EvnPrescr_pid -- внутри КВС есть движение текущего отделения
                    inner join Evn e on e.Evn_id = ES.EvnSection_pid -- КВС для фильтрации по датам
                    left join v_EvnPS eps on 1=0 -- квс не нужна, но может использоваться в фильтрах
                    left join lateral(
                        SELECT -- по одному назначению вряд ли будет больше 500 наблюдений
                            EvnPrescrObserv_id, PrescriptionStatusType_id,
                            EvnPrescrObserv_Descr,
                            EvnPrescrObserv_setDT,
                            EvnPrescrObserv_didDT,
                            EvnPrescrObserv_setTime,
                            EvnPrescrObserv_IsExec,
                            ObservTimeType_id,
                            pmUser_updID
                        from v_EvnPrescrObserv EPO
                        WHERE EP.PrescriptionType_id = 10
                            and EPO.Lpu_id = '13101850'
                            and EPO.EvnPrescrObserv_pid = EP.EvnPrescr_id
                            -- оказвыается может и больше 500 по одному назначению. Сделаем огрничения по дате.
                            and cast(EPO.EvnPrescrObserv_setDT as date) >= cast('2022-05-08' as date)
                            and cast(EPO.EvnPrescrObserv_setDT as date) <= cast('2022-05-08' as date)
                        limit 500
                    ) AS Obs on true
                     left join lateral(
                SELECT
                    EvnPrescrDiet_id, PrescriptionStatusType_id,
                    EvnPrescrDiet_Descr,
                    EvnPrescrDiet_setDT,
                    EvnPrescrDiet_didDT,
                    EvnPrescrDiet_setTime,
                    EvnPrescrDiet_IsExec,
                    PrescriptionDietType_id
                from v_EvnPrescrDiet EPD
                WHERE EP.PrescriptionType_id = 2
                and EPD.Lpu_id = '13101850'
                and EPD.EvnPrescrDiet_pid = EP.EvnPrescr_id
                limit 500
            ) Diet on true
            left join lateral (
                SELECT
                    EvnPrescrRegime_id, PrescriptionStatusType_id,
                    EvnPrescrRegime_Descr,
                    EvnPrescrRegime_setDT,
                    EvnPrescrRegime_didDT,
                    EvnPrescrRegime_setTime,
                    EvnPrescrRegime_IsExec,
                    PrescriptionRegimeType_id
                from v_EvnPrescrRegime WHERE EvnPrescrRegime_pid = EP.EvnPrescr_id
                limit 10000
            ) AS Regime ON true
                where EP.PrescriptionType_id != 4
                    and cast(E.Evn_setDT as date) <= cast('2022-05-08' as date) and coalesce(cast(E.Evn_disDT as date), cast('2022-05-08' as date)) >= cast('2022-05-08' as date)
                    and ES.LpuSection_id = '890101000000272'
                    and EP.Lpu_id = '13101850'
                     and ES.LeaveType_id is null

                union all

                -- назначения в приёмном движении (если они сохраняются на приёмное движение)
                select
                    EP.PrescriptionType_id,
                    EP.Person_id,
                    EP.pmUser_insID,
                    EP.pmUser_updID,
                    EP.EvnPrescr_id,
                    EP.EvnPrescr_pid,
                    EP.EvnPrescr_rid,
                    coalesce(Regime.EvnPrescrRegime_didDT,Diet.EvnPrescrDiet_didDT,Obs.EvnPrescrObserv_didDT,EP.EvnPrescr_didDT) as EvnPrescr_didDT,
                    EP.PersonEvn_id,
                    EP.Server_id,
                    EP.Lpu_id,
                    EP.PrescrFailureType_id,
                    PFT.PrescrFailureType_Name,
                    EP.EvnPrescr_insDT,
                    EP.EvnPrescr_IsCito,
                    --EP.PrescriptionStatusType_id,
                    EP.EvnPrescr_Descr,
                    EP.EvnPrescr_setDT,
                    EP.EvnPrescr_setTime,
                    EP.EvnPrescr_IsExec,
                    ES.Diag_id,
                    ES.EvnSection_id,
                    ES.LpuSectionWard_id,
                    coalesce(Regime.EvnPrescrRegime_IsExec,Diet.EvnPrescrDiet_IsExec,Obs.EvnPrescrObserv_IsExec,EP.EvnPrescr_IsExec,1) as EvnPrescrDay_IsExec,
                    coalesce(Regime.PrescriptionStatusType_id,Diet.PrescriptionStatusType_id,Obs.PrescriptionStatusType_id,EP.PrescriptionStatusType_id) as PrescriptionStatusType_id,
                    coalesce(Regime.EvnPrescrRegime_Descr,Diet.EvnPrescrDiet_Descr,Obs.EvnPrescrObserv_Descr,EP.EvnPrescr_Descr) as EvnPrescrDay_Descr,
                    coalesce(Regime.EvnPrescrRegime_setDT,Diet.EvnPrescrDiet_setDT,Obs.EvnPrescrObserv_setDT,EP.EvnPrescr_setDT) as EvnPrescrDay_setDT,
                    coalesce(Regime.EvnPrescrRegime_setTime,Diet.EvnPrescrDiet_setTime,Obs.EvnPrescrObserv_setTime,EP.EvnPrescr_setTime) as EvnPrescrDay_setTime,
                    coalesce(Regime.EvnPrescrRegime_id,Diet.EvnPrescrDiet_id,Obs.EvnPrescrObserv_id,EP.EvnPrescr_id) as EvnPrescrDay_id,
                    Regime.PrescriptionRegimeType_id,
                    Diet.PrescriptionDietType_id,
                    Obs.ObservTimeType_id,
                    Obs.pmUser_updID as userUPD,
                    EP.EvnCourse_id
                from v_EvnPrescr EP
                    left join v_PrescrFailureType PFT on EP.PrescrFailureType_id = PFT.PrescrFailureType_id
                    inner join v_EvnSection ES2 on ES2.EvnSection_id = EP.EvnPrescr_pid
                    inner join v_EvnSection ES on ES.EvnSection_pid = ES2.EvnSection_pid -- внутри КВС есть движение текущего отделения
                    inner join Evn e on e.Evn_id = ES.EvnSection_pid -- КВС для фильтрации по датам
                    left join v_EvnPS eps on 1=0 -- квс не нужна, но может использоваться в фильтрах
                    left join lateral(
                        SELECT -- по одному назначению вряд ли будет больше 500 наблюдений
                            EvnPrescrObserv_id, PrescriptionStatusType_id,
                            EvnPrescrObserv_Descr,
                            EvnPrescrObserv_setDT,
                            EvnPrescrObserv_didDT,
                            EvnPrescrObserv_setTime,
                            EvnPrescrObserv_IsExec,
                            ObservTimeType_id,
                            pmUser_updID
                        from v_EvnPrescrObserv EPO
                        WHERE EP.PrescriptionType_id = 10
                            and EPO.Lpu_id = '13101850'
                            and EPO.EvnPrescrObserv_pid = EP.EvnPrescr_id
                            -- оказвыается может и больше 500 по одному назначению. Сделаем огрничения по дате.
                            and cast(EPO.EvnPrescrObserv_setDT as date) >= cast('2022-05-08' as date)
                            and cast(EPO.EvnPrescrObserv_setDT as date) <= cast('2022-05-08' as date)
                        limit 500
                    ) AS Obs on true
                     left join lateral(
                SELECT
                    EvnPrescrDiet_id, PrescriptionStatusType_id,
                    EvnPrescrDiet_Descr,
                    EvnPrescrDiet_setDT,
                    EvnPrescrDiet_didDT,
                    EvnPrescrDiet_setTime,
                    EvnPrescrDiet_IsExec,
                    PrescriptionDietType_id
                from v_EvnPrescrDiet EPD
                WHERE EP.PrescriptionType_id = 2
                and EPD.Lpu_id = '13101850'
                and EPD.EvnPrescrDiet_pid = EP.EvnPrescr_id
                limit 500
            ) Diet on true
            left join lateral (
                SELECT
                    EvnPrescrRegime_id, PrescriptionStatusType_id,
                    EvnPrescrRegime_Descr,
                    EvnPrescrRegime_setDT,
                    EvnPrescrRegime_didDT,
                    EvnPrescrRegime_setTime,
                    EvnPrescrRegime_IsExec,
                    PrescriptionRegimeType_id
                from v_EvnPrescrRegime WHERE EvnPrescrRegime_pid = EP.EvnPrescr_id
                limit 10000
            ) AS Regime ON true
                where EP.PrescriptionType_id != 4
                    and cast(E.Evn_setDT as date) <= cast('2022-05-08' as date) and coalesce(cast(E.Evn_disDT as date), cast('2022-05-08' as date)) >= cast('2022-05-08' as date)
                    and ES.LpuSection_id = '890101000000272'
                    and ES2.EvnSection_IsPriem = 2
                    and EP.Lpu_id = '13101850'
                     and ES.LeaveType_id is null
            ), EvnPrescrAll as (
                select
                    EP.PrescriptionType_id,
                    EP.EvnPrescr_id,
                    EP.EvnPrescr_pid,
                    EP.EvnPrescr_rid,
                    EP.EvnPrescr_didDT,
                    EP.Person_id,
                    EP.PersonEvn_id,
                    EP.Server_id,
                    PS.Sex_id as Sex_id,
                    PS.Person_Birthday as Person_Birthday,
                    PS.Person_Surname as Person_Surname,
                    PS.Person_Firname as Person_Firname,
                    PS.Person_Secname as Person_Secname,
                    EP.Lpu_id,
                    EP.PrescrFailureType_id,
                    EP.PrescrFailureType_Name,
                    EP.Diag_id,
                    EP.EvnSection_id,
                    EP.LpuSectionWard_id,
                    EP.EvnPrescr_insDT,
                    coalesce(PMUI.pmUser_Name, '') as pmUser_insName,
                    coalesce(PMUU.pmUser_Name, '') as pmUser_execName,
                    coalesce(EP.EvnPrescr_IsCito, 1) as EvnPrescr_IsCito,
                    EP.EvnPrescrDay_IsExec,
                    EP.PrescriptionStatusType_id,
                    EP.EvnPrescrDay_Descr,
                    EP.EvnPrescrDay_setDT,
                    EP.EvnPrescrDay_setTime,
                    EP.EvnPrescrDay_id,
                    EP.PrescriptionRegimeType_id,
                    EP.PrescriptionDietType_id,
                    EP.ObservTimeType_id,
                    PMUI.pmUser_Medpersonal_id as "MedPersonal_id",
                    EP.userUPD,
                    EP.EvnCourse_id
                from EvnPrescrFirst EP
                inner join lateral (select * from v_PersonState PS where PS.Person_id = EP.Person_id limit 1) PS on true
                left join v_pmUser PMUI on PMUI.pmUser_id = EP.pmUser_insID
                left join v_pmUser PMUU on PMUU.pmUser_id = EP.pmUser_updID
                
                where 1 = 1
                
            )
            
                SELECT 
                EP.EvnPrescrDay_id as "EvnPrescrDay_id",
                EP.EvnPrescr_id as "EvnPrescr_id",
                EP.EvnPrescr_pid as "EvnPrescr_pid",
                EP.EvnPrescr_rid as "EvnPrescr_rid",
                EP.Diag_id as "Diag_id",
                EP.Person_id as "Person_id",
                EP.PersonEvn_id as "PersonEvn_id",
                EP.Server_id as "Server_id",
                EP.PrescrFailureType_id as "PrescrFailureType_id",
                EP.PrescrFailureType_Name as "PrescrFailureType_Name",
                EP.PrescriptionType_id as "PrescriptionType_id",
                EP.EvnPrescr_IsCito as "EvnPrescr_IsCito",
                EP.EvnPrescrDay_IsExec as "EvnPrescr_IsExec",
                to_char(EP.EvnPrescrDay_setDT, 'dd.mm.yyyy') as "EvnPrescr_setDate",
                case
                    when TTMS.TimetableMedService_id is not null then
                        to_char(TTMS.TimetableMedService_begTime, 'dd.mm.yyyy HH24:MI')
                    when TTR.TimetableResource_id is not null then
                        to_char(TTR.TimetableResource_begTime, 'dd.mm.yyyy HH24:MI')
                    when EQ.EvnQueue_id is not null then
                        null
                    when arr_time.EvnPrescr_setTime is not null then
                            to_char(EP.EvnPrescrDay_setDT, 'dd.mm.yyyy') || '  <br />(' || arr_time.EvnPrescr_setTime || ')'
                    when arr_time.EvnPrescr_allTime is not null and EP.EvnPrescrDay_IsExec = 2 then
                        to_char(EP.EvnPrescrDay_setDT, 'dd.mm.yyyy')
                    else
                        to_char(EP.EvnPrescrDay_setDT, 'dd.mm.yyyy HH24:MI')
                end	as "EvnPrescr_planDate",
                case when EP.EvnPrescrDay_IsExec = 2 then
                    to_char(coalesce(EU.EvnUsluga_disDT, EP.EvnPrescr_didDT), 'dd.mm.yyyy HH24:MI')
                else
                    null
                end as "EvnPrescr_execDate",
                COALESCE(arr_time.EvnPrescr_setTime,
                    to_char(TTMS.TimetableMedService_begTime, 'HH24:MI'), to_char(EP.EvnPrescrDay_setTime, 'HH24:MI')) as "EvnPrescr_setTime",
                arr_time.EvnPrescr_execTime as "EvnPrescr_execTime",
                RTRIM(LTRIM(coalesce(EP.Person_Surname, ''))) || ' ' || RTRIM(LTRIM(coalesce(EP.Person_Firname, ''))) || ' ' || RTRIM(LTRIM(coalesce(EP.Person_Secname, ''))) as "Person_FIO",
                to_char(EP.Person_Birthday, 'dd.mm.yyyy') as "Person_Birthday",
                coalesce(PT.PrescriptionType_Code, 0) as "PrescriptionType_Code",
                coalesce(PT.PrescriptionType_Name, '') as "PrescriptionType_Name",
                to_char(EP.EvnPrescr_insDT, 'dd.mm.yyyy HH24:MI') as "EvnPrescr_insDT",
                YN.YesNo_Name as "IsExec_Name",
                EP.EvnPrescrDay_Descr as "EvnPrescr_Descr",
                '' as "LpuSectionProfile_Name",
                EP.pmUser_insName as "pmUser_insName",
                LSW.LpuSectionWard_id as "LpuSectionWard_id",
                EP.Sex_id as "Sex_id",
                EP.EvnSection_id as "EvnSection_id",
                coalesce(LSW.LpuSectionWard_Name, 'Без палаты') as "LpuSectionWard_Name",
                LSW.LpuSectionWard_id as "LpuSectionWard_id",
                ED.EvnDirection_id as "EvnDirection_id",
                --1
                coalesce(PRT.PrescriptionRegimeType_Name, '')  as "PrescriptionRegimeType_Name",
                --2
                coalesce(PDT.PrescriptionDietType_Name, '') as "PrescriptionDietType_Name",
                --10
                EP.ObservTimeType_id as "ObservTimeType_id",
                coalesce(OTT.ObservTimeType_Name, '') as "ObservTimeType_Name",
                0 as "PrescriptionTreatType_Code",
                '' as "PrescriptionTreatType_Name",
                coalesce(ECT.EvnCourseTreat_MaxCountDay, 0) as "EvnPrescrTreat_CountInDay",
                coalesce(PIT.PrescriptionIntroType_Name, '') as "PrescriptionIntroType_Name",
                coalesce(PFT.PerformanceType_Name, '') as "PerformanceType_Name",
                Treat.EvnPrescrTreat_PrescrCount as "PrescrCntDay",
                null as "EvnPrescrTreatDrug_id",
                null as "EvnPrescrTreatDrug_KolvoEd",
                null as "DrugForm_Name",
                null as "EvnPrescrTreatDrug_Kolvo",
                null as "Okei_NationSymbol",
                null as "Drug_Name",
                null as "DrugTorg_Name",
                0 as "cntDrug",
                null as "DoseDay",
                null as "FactCntDay",
                coalesce(ECT.EvnCourseTreat_MaxCountDay::varchar,ECP.EvnCourseProc_MaxCountDay::varchar, '') as "CountInDay",
                coalesce(ECT.EvnCourseTreat_Duration::varchar,ECP.EvnCourseProc_Duration::varchar, '') as "CourseDuration",
                coalesce(ECT.EvnCourseTreat_ContReception::varchar,ECP.EvnCourseProc_ContReception::varchar, '') as "ContReception",
                coalesce(ECT.EvnCourseTreat_Interval::varchar,ECP.EvnCourseProc_Interval::varchar, '') as "Interval",
                coalesce(DTP.DurationType_Nick, '') as "DurationTypeP_Nick",
                coalesce(DTN.DurationType_Nick, '') as "DurationTypeN_Nick",
                coalesce(DTI.DurationType_Nick, '') as "DurationTypeI_Nick",
                case when EU.EvnUsluga_id is null then 1 else 2 end as "EvnPrescr_IsHasEvn",
                case
                    when EP.PrescriptionType_id in (6,11,13) then 1
                    else null
                end as "TableUsluga_id",
                UC.UslugaComplex_Name as "UslugaComplex_Name",
                UC.UslugaComplex_id as "UslugaComplex_id",
                case
                    when EP.PrescriptionType_id in (6,11,13) then 1
                    else null
                end as "cntUsluga",
                case when EP.EvnPrescrDay_IsExec = 2 then
                    case
                        when EP.PrescriptionType_id IN (6,7,11,12,13,14) then MP.Person_SurName || ' ' || coalesce(MP.Person_FirName, '') || ' ' || coalesce(MP.Person_SecName, '')
                        when EP.PrescriptionType_id = 10 then ObsPMU.PMUser_Name
                      	else EP.pmUser_execName
                  	end
                else ''
                end as "pmUser_execName",
                MP.MedPersonal_id as "MedPersonal_id",
                CASE WHEN PQ.PersonQuarantine_id is not null THEN 'true' ELSE 'false' END as "PersonQuarantine_IsOn",
                to_char(PQ.PersonQuarantine_begDT, 'DD.MM.YYYY') as "PersonQuarantine_begDT",
                EP.EvnCourse_id as "EvnCourse_id"
                
                FROM
                
                EvnPrescrAll EP
                left join v_LpuSectionWard LSW on LSW.LpuSectionWard_id = EP.LpuSectionWard_id
                left join lateral(
                    select
                        coalesce(ED.EvnDirection_id, epd.EvnDirection_id) as EvnDirection_id,
                        ED.EvnStatus_id,
                        ED.MedService_id
                    from v_EvnPrescrDirection epd
                    inner join v_EvnDirection_all ED on epd.EvnDirection_id = ED.EvnDirection_id
                        and ED.EvnDirection_failDT is null
                        and coalesce(ED.EvnStatus_id, 16) not in (12,13)
                    where epd.EvnPrescr_id = EP.EvnPrescr_id
                    order by epd.EvnPrescrDirection_insDT desc
                    limit 1
                ) ED on true
                left join lateral(
                    Select TimetableMedService_id, TimetableMedService_begTime from v_TimetableMedService_lite TTMS where TTMS.EvnDirection_id = ED.EvnDirection_id limit 1
                ) TTMS on true
                left join lateral(
                    Select TimetableResource_id, TimetableResource_begTime from v_TimetableResource_lite TTR where TTR.EvnDirection_id = ED.EvnDirection_id limit 1
                ) TTR on true
                left join lateral(
                    Select EQ.EvnQueue_id, EQ.EvnQueue_setDate from v_EvnQueue EQ where EQ.EvnDirection_id = ED.EvnDirection_id and EQ.EvnQueue_failDT is null limit 1
                ) EQ on true
                inner join PrescriptionType PT on PT.PrescriptionType_id = EP.PrescriptionType_id
                left join YesNo YN on YN.YesNo_id = EP.EvnPrescrDay_IsExec
                --1
                left join PrescriptionRegimeType PRT on EP.PrescriptionType_id = 1 and PRT.PrescriptionRegimeType_id = EP.PrescriptionRegimeType_id
                --2
                left join PrescriptionDietType PDT on EP.PrescriptionType_id = 2 and PDT.PrescriptionDietType_id = EP.PrescriptionDietType_id
                --5
                left join v_EvnPrescrTreat Treat on Treat.EvnPrescrTreat_id = EP.EvnPrescr_id
                left join v_EvnCourseTreat ECT on Treat.EvnCourse_id = ECT.EvnCourseTreat_id
                left join v_EvnCourseProcTreatLink ECPTL on -- действующие связки курсов ЛЛ с курсами МП
                    ECPTL.EvnCourseTreat_id = ECT.EvnCourseTreat_id
                    and cast(ECPTL.EvnCourseProcTreatLink_begDate as date) <= cast('2022-05-08' as date) -- связка действует на момент завершения промежутка, на который формируется список назначений
                    and (cast(ECPTL.EvnCourseProcTreatLink_endDate as date) > cast('2022-05-08' as date)
                        or ECPTL.EvnCourseProcTreatLink_endDate is null)
                left join PrescriptionIntroType PIT on ECT.PrescriptionIntroType_id = PIT.PrescriptionIntroType_id
                left join PerformanceType PFT on  ECT.PerformanceType_id = PFT.PerformanceType_id
                --6
                left join v_EvnPrescrProc EPPR on EP.PrescriptionType_id = 6 and EPPR.EvnPrescrProc_id = EP.EvnPrescr_id
                left join v_EvnCourseProc ECP on EP.PrescriptionType_id = 6 and EPPR.EvnCourse_id = ECP.EvnCourseProc_id
                --5,6
                left join DurationType DTP on coalesce(ECP.DurationType_id,ECT.DurationType_id) = DTP.DurationType_id
                left join DurationType DTN on coalesce(ECP.DurationType_recid,ECT.DurationType_recid) = DTN.DurationType_id
                left join DurationType DTI on coalesce(ECP.DurationType_intid,ECT.DurationType_intid) = DTI.DurationType_id
                --10
                left join ObservTimeType OTT on EP.PrescriptionType_id = 10 and OTT.ObservTimeType_id = EP.ObservTimeType_id
                left join v_pmUserCache ObsPMU on ObsPMU.PMUser_id = EP.userUPD
                --11
                left join v_EvnUsluga_all EUAll on ED.EvnDirection_id = EuAll.EvnDirection_id
                left join v_MedPersonal MP on MP.MedPersonal_id = EUAll.MedPersonal_id AND MP.Lpu_id = EUAll.Lpu_id
                --left join v_EvnPrescrLabDiag EPLD on EP.PrescriptionType_id = 11 and EPLD.EvnPrescrLabDiag_id = EP.EvnPrescr_id
                left join lateral(
                    select * from v_EvnPrescrLabDiag EPLD where EP.PrescriptionType_id = 11 and EvnPrescrLabDiag_id = EP.EvnPrescr_id limit 100
                ) EPLD on true
                --13,6
                --left join v_EvnPrescrConsUsluga EPCU on EP.PrescriptionType_id = 13 and EPCU.EvnPrescrConsUsluga_id = EP.EvnPrescr_id
                left join lateral(
                    select * from v_EvnPrescrOperBlock where EP.PrescriptionType_id = 7 and EvnPrescrOperBlock_id = EP.EvnPrescr_id limit 100
                ) EPOB on true
                left join lateral(
                    select * from v_EvnPrescrConsUsluga where EP.PrescriptionType_id = 13 and EvnPrescrConsUsluga_id = EP.EvnPrescr_id limit 100
                ) EPCU on true
                left join v_UslugaComplex UC on UC.UslugaComplex_id = coalesce(EPPR.UslugaComplex_id,EPLD.UslugaComplex_id,EPCU.UslugaComplex_id,EPOB.UslugaComplex_id)
                left join lateral(
                    select EvnUsluga_id, coalesce(EvnUsluga_disDT, EvnUsluga_setDT) as EvnUsluga_disDT from v_EvnUsluga
                    where EP.EvnPrescrDay_IsExec = 2 and UC.UslugaComplex_id is not null and EvnPrescr_id = EP.EvnPrescr_id
                    limit 1
                ) EU on true
                left join lateral (
                    select PQ.*
                    from v_PersonQuarantine PQ
                    where PQ.Person_id = EP.Person_id
                    and PQ.PersonQuarantine_endDT is null
                    limit 1
                ) PQ on true
                left join lateral(Select null as EvnPrescr_setTime, null as EvnPrescr_execTime, null as EvnPrescr_allTime) arr_time on true
                 WHERE 
                (1=1)
                
                and cast(coalesce(TTMS.TimetableMedService_begTime,TTR.TimetableResource_begTime,EQ.EvnQueue_setDate,EP.EvnPrescrDay_setDT) as date) >= cast('2022-05-08' as date)
                and cast(coalesce(TTMS.TimetableMedService_begTime,TTR.TimetableResource_begTime,EQ.EvnQueue_setDate,EP.EvnPrescrDay_setDT) as date) <= cast('2022-05-08' as date)
                and ECPTL.EvnCourseProcTreatLink_id is null
                
                
                        ORDER BY
                            
                EP.EvnPrescrDay_setDT,
                EP.PrescriptionType_id,
                EP.EvnPrescr_id
                
                OFFSET 0 ROWS
                FETCH NEXT 100 ROWS ONLY
                
