
            --variables
            with mv as (
                select
                dbo.tzGetDate() as dt
            )
            --end variables
        
            select
                 count( distinct EUP.EvnUslugaPar_id  ) AS cnt 
            from
                -- from
         dbo.v_PersonState PS  inner join v_EvnUslugaPar EUP on EUP.Person_id = PS.Person_id and (
                EUP.Lpu_id = '47'
                OR EUP.Lpu_uid = '47'
            )
            left join v_EvnCostPrint ecp on ecp.Evn_id = EUP.EvnUslugaPar_id
            left join v_LpuSection LS on LS.LpuSection_id = EUP.LpuSection_uid
            left join v_Lpu lpu on lpu.Lpu_id = LS.Lpu_id
            left join lateral(
                select Person_Fio
                from v_MedPersonal
                where MedPersonal_id = EUP.MedPersonal_id
                limit 1
            ) MP on true
            left join Usluga on Usluga.Usluga_id = EUP.Usluga_id
            left join UslugaComplex on UslugaComplex.UslugaComplex_id = EUP.UslugaComplex_id
            left join v_Evn EvnParent on EvnParent.Evn_id = EUP.EvnUslugaPar_pid
            left join v_PayType PT on PT.PayType_id = EUP.PayType_id
            left join v_MedStaffFact MedStaffFact on MedStaffFact.MedStaffFact_id = EUP.MedStaffFact_id
            left join v_PostMed PostMed on PostMed.PostMed_id = MedStaffFact.Post_id
            left join v_EvnDirection_all ED on EUP.EvnDirection_id = ED.EvnDirection_id
            left join v_Lpu LD on LD.Lpu_id = ED.Lpu_sid
            left join Org on Org.Org_id = ED.Org_sid
            left join v_Lpu L ON L.Lpu_id = ED.Lpu_sid -- NGS
            left join v_Lpu L2 ON L2.Lpu_id = EUP.Lpu_did -- NGS
            left join v_Lpu L3 on L3.Org_id = EUP.Org_uid
            left join Org O2 on O2.Org_id = EUP.Org_did
        
                left join lateral(
                    select EvnXml.EvnXml_id
                    from v_EvnXml  EvnXml
                    where Evn_id = EUP.EvnUslugaPar_id
                    order by EvnXml_insDT desc
                    limit 1
                ) doc on true
            
                        -- end from
                    where
                        -- where
                        (1 = 1) and eup.EvnUslugaPar_setDate is not null and EUP.LpuSection_uid = '450101000005570' AND coalesce(ED.LpuSection_id, EUP.LpuSection_did) = '450101000005582' AND CASE WHEN ED.PrehospDirect_id IS NOT NULL THEN ED.PrehospDirect_id ELSE EUP.PrehospDirect_id END = '1' and coalesce(L.Org_id, EUP.Org_did) = '47' and (EvnParent.EvnClass_SysNick <> 'EvnUslugaPar' or EvnParent.EvnClass_SysNick is null)
                        -- end where
                
                    
                
