
            Select
                c.Contragent_id as "Contragent_id",
                c.ContragentType_id as "ContragentType_id",
                rtrim(ct.ContragentType_Name) as "ContragentType_Name",
                c.Lpu_id as "Lpu_id",
                c.Org_id as "Org_id",
                ot.OrgType_SysNick as "OrgType_SysNick",
                o.Server_id as "OrgServer_id",
                c.Org_pid as "Org_pid",
                c.OrgFarmacy_id as "OrgFarmacy_id",
                c.LpuSection_id as "LpuSection_id",
                c.Contragent_Code as "Contragent_Code",
                RTrim(c.Contragent_Name) as "Contragent_Name",
                to_char(ced.BegDate, 'DD.MM.YYYY') as "BegDate",

                to_char(ced.EndDate, 'DD.MM.YYYY') as "EndDate"

            from
                v_Contragent c

                left join v_ContragentType ct  on ct.ContragentType_id = c.ContragentType_id

                left join v_Org o  on o.Org_id = c.Org_id

                left join v_OrgType ot  on ot.OrgType_id = o.OrgType_id

                left join OrgFarmacy ofr  on ofr.OrgFarmacy_id = c.OrgFarmacy_id

                left join v_LpuSection ls  on ls.LpuSection_id = c.LpuSection_id

                LEFT JOIN LATERAL (

                    select
                         COALESCE(ContragentExpDates.BegDate, c.Contragent_insDT) as BegDate,

                         ContragentExpDates.EndDate
                    from
                        GetContragentExpDates(c.Contragent_id, c.ContragentType_id) ContragentExpDates
                ) ced ON true
            where
                (1=1) and (ofr.Region_id is null or ofr.Region_id = 50) and (c.Lpu_id is null or c.Lpu_id = 0)
            order by
                c.Contragent_Code, c.Contragent_Name
        
