--- Список работающих Подразделений - отделений 
select 
    L.Lpu_Name as "ЛПУ",
    fs.frmounit_moid as "ОИД мед. организации",
    L.lpu_nick as "ЛПУ сокр.",
    LB.lpubuilding_name "Здание",
    fs.frmounit_oid as "ОИД подразделения",
    LU.LpuUnit_Name "Подразделение",
    FSc.frmosection_oid as "ОИД отделения",
    LS.LpuSection_Name "Отделение",
    MSF.person_fio "ФИО врача",
    MSF.person_birthday::date "Дата рождения",
    MSF.person_snils "СНИЛС",
    P."name" "Должность",
    MSF.medstafffact_stavka  as "Ставка"
from dbo.v_Lpu L
inner join dbo.v_LpuBuilding LB on LB.Lpu_id = L.Lpu_id
    and coalesce(L.Lpu_IsTest, 1) = 1
  and L.Lpu_begDate < current_date + interval '1 days'
  and coalesce(L.Lpu_endDate, current_date) >= current_date
  and (LB.LpuBuilding_begDate < current_date + interval '1 days' or LB.LpuBuilding_begDate is null)
  and (LB.LpuBuilding_endDate >= current_date or LB.LpuBuilding_endDate is null)
left join dbo.v_LpuUnit LU on LU.LpuBuilding_id = LB.LpuBuilding_id   
  and (LU.LpuUnit_begDate < current_date + interval '1 days' or LU.LpuUnit_begDate is null)
  and (LU.LpuUnit_endDate >= current_date or LU.LpuUnit_endDate is null) 
left join dbo.v_LpuUnitType LUT on LUT.LpuUnitType_id = LU.LpuUnitType_id  
left join dbo.v_LpuSection LS on LS.LpuUnit_id = LU.LpuUnit_id
  and (LS.LpuSection_setDate < current_date + interval '1 days' or LS.LpuSection_setDate is null)
  and (LS.LpuSection_disDate >= current_date or LS.LpuSection_disDate is null)
left join nsi.frmounit fs on LU.frmounit_id = fs.frmounit_id
left join nsi.frmosection FSc on FSc.frmosection_id = LS.frmosection_id and fs.frmounit_oid = FSc.frmounit_oid and FSc.frmosection_moid = fs.frmounit_moid 
inner join dbo.v_MedStaffFact MSF on MSF.lpusection_id = LS.lpusection_id and (msf.workdata_enddate>now() or msf.workdata_enddate is null) and MSF.lpubuilding_id = LB.lpubuilding_id 
inner join persis.Post P on P.id = MSF.post_id and (p.endDT>now() or p.endDT is null or date_part('year', p.endDT) = 1900) and (msf.workdata_enddate>now() or msf.workdata_enddate is null)
where --L.lpu_name = 'ГБУЗ МОСКОВСКОЙ ОБЛАСТИ "БАЛАШИХИНСКАЯ ОБЛАСТНАЯ БОЛЬНИЦА"' and 
MSF.lpusection_id is not null and MSF.lpuunit_id is not null and MSF.lpubuilding_id is not null
