
with param as (select
    cast($1 as bigint) as p_lpu_id, 
    cast($2 as text) as p_lpufiliallist, 
    cast($3 as bigint) as p_lpubuilding_id, 
    cast($4 as bigint) as p_lpuunit_id, 
    cast($5 as bigint) as p_lpusection_id, 
    cast($6 as bigint) as p_lpusectionbedprofile_id,
    cast($7 as bigint) as p_lpuunittype_id, 
    cast($8 as bigint) as p_paytype_id, 
    cast(to_timestamp($9,'dd.mm.yyyy') as timestamp) as p_begdate, 
    cast(to_timestamp($10,'dd.mm.yyyy') as timestamp) as p_enddate, 
    cast($11 as time) as p_stactime, 
    cast($12 as bigint) as p_order413, 
    cast(1 as bigint) as p_printstring,
    cast($13 as bigint) as p_NeedReanim,
    cast($14 as bigint) as p_national
  
  )

,LpuP as (
				select L.Lpu_id
					,cast(L.Lpu_begDate as date) as Lpu_begDate
					,cast(L.Lpu_endDate as date) as Lpu_endDate
					,cast(p_begdate + case when coalesce(p_order413, 2) = 2 then -1 else 0 end  * interval '1 day' + coalesce(p_stactime, cast('09:00' as time))  as timestamp ) as LS_begDate
					,cast(p_enddate + coalesce(p_stactime, cast('09:00' as time)) + case when coalesce(p_order413, 2) = 2 then -1 else 0 end * interval '1 day' as timestamp )
							as LS_endDate
					,cast(p_begdate + coalesce(p_stactime, cast('09:00' as time)) + (1 - coalesce(p_order413, 2)) * interval '1 day' as timestamp ) as Stac_begDT
					
					,cast(case when p_enddate <= current_date then p_enddate else current_date end + coalesce(p_stactime, cast('09:00' as time)) + (2 - coalesce(p_order413, 2)) * interval '1 day' as timestamp )
										as Stac_endDT
					,coalesce(p_stactime, cast('09:00' as time)) as StacTime
				from param 
         inner join rpt.GetLpu_succession_pg (p_Lpu_id, (case when coalesce(p_Order413, 2) = 2 then - interval '1 day' else interval '0 day' end + p_begDate), (case when coalesce(p_Order413, 2) = 2 then interval '0 day' else interval '1 day' end + p_endDate)) as L on true
				where	1 = 1
				  and CAST(p_begdate as DATE) <= CAST(current_date as DATE)
				  and extract(year from p_begdate) = extract(year from p_enddate)
			)
, lp_month as (
select b.n
		,b.month_name
		,cast(case when cast((b.LS_begDate || cast(extract(year from p_enddate) as varchar)) as date) < p_begdate 
					then p_begdate + coalesce(p_stactime, cast('09:00' as time)) 
					else cast((b.LS_begDate || cast(extract(year from p_enddate) + case when b.n in (14) then 1 else 0 end as varchar)) as date) + coalesce(p_stactime, cast('09:00' as time)) end 
						+ case when coalesce(p_order413, 2) = 2 then -1 else 0 end * interval '1 day' as timestamp ) as LS_begDate
		,cast(case when cast((b.LS_endDate || cast(extract(year from p_enddate) + case when b.n in (13,14) then 1 else 0 end as varchar)) as date) - 1  * interval '1 day' 
							+ case when coalesce(p_order413, 2) = 2 then -1 else 0 end * interval '1 day' > p_enddate
					then p_enddate + coalesce(p_stactime, cast('09:00' as time))
					else cast((b.LS_endDate || cast(extract(year from p_enddate) + case when b.n in (13,14) then 1 else 0 end as varchar)) as date) - 1  * interval '1 day' 
							+ case when coalesce(p_order413, 2) = 2 then -1 else 0 end * interval '1 day' + coalesce(p_stactime, cast('09:00' as time)) 
					end as timestamp ) as LS_endDate
		,cast(case when cast((b.LS_begDate || cast(extract(year from p_enddate) as varchar)) as date) < p_begdate then p_begdate + coalesce(p_stactime, cast('09:00' as time)) 
		      else cast((b.LS_begDate || cast(extract(year from p_enddate) + case when b.n in (14) then 1 else 0 end as varchar)) 
									|| ' ' || coalesce(cast(p_stactime as varchar), '09:00:00') as timestamp) end 
													 + case when coalesce(p_order413, 2) = 2 then -1 else 0 end * interval '1 day' as timestamp ) as Stac_begDT
		,cast(case when cast((b.LS_endDate || cast(extract(year from p_enddate) + case when b.n in (13,14) then 1 else 0 end as varchar)) 
									|| ' ' || coalesce(cast(p_stactime as varchar), '09:00:00') as timestamp) - 1 * interval '1 day' 
																			+ case when coalesce(p_order413, 2) = 2 then -1 else 0 end * interval '1 day' > p_enddate
						then p_enddate + coalesce(p_stactime, cast('09:00' as time)) + case when coalesce(p_order413, 2) = 2 then 0 else 1 end * interval '1 day'
						else cast((b.LS_endDate || cast(extract(year from p_enddate) + case when b.n in (13,14) then 1 else 0 end as varchar)) 
									|| ' ' || coalesce(cast(p_stactime as varchar), '09:00:00') as timestamp) - 1 * interval '1 day' 
																			+ case when coalesce(p_order413, 2) = 2 then -1 else 0 end * interval '1 day'
					end as timestamp ) as Stac_endDT
from param 
         inner join (select 1 as n
			,'Январь' as month_name
			,'01.01.' as LS_begDate
			,'01.02.' as LS_endDate
		union all
	select 2 as n
			,'Февраль' as month_name
			,'01.02.' as LS_begDate
			,'01.03.' as LS_endDate
		union all
	select 3 as n
			,'Март' as month_name
			,'01.03.' as LS_begDate
			,'01.04.' as LS_endDate
		union all
	select 4 as n
			,'Апрель' as month_name
			,'01.04.' as LS_begDate
			,'01.05.' as LS_endDate
		union all
	select 5 as n
			,'Май' as month_name
			,'01.05.' as LS_begDate
			,'01.06.' as LS_endDate
		union all
	select 6 as n
			,'Июнь' as month_name
			,'01.06.' as LS_begDate
			,'01.07.' as LS_endDate
		union all
	select 7 as n
			,'За полугодие' as month_name
			,'01.01.' as LS_begDate
			,'01.07.' as LS_endDate
		union all
	select 8 as n
			,'Июль' as month_name
			,'01.07.' as LS_begDate
			,'01.08.' as LS_endDate
		union all
	select 9 as n
			,'Август' as month_name
			,'01.08.' as LS_begDate
			,'01.09.' as LS_endDate
		union all
	select 10 as n
			,'Сентябрь' as month_name
			,'01.09.' as LS_begDate
			,'01.10.' as LS_endDate
		union all
	select 11 as n
			,'Октябрь' as month_name
			,'01.10.' as LS_begDate
			,'01.11.' as LS_endDate
		union all
	select 12 as n
			,'Ноябрь' as month_name
			,'01.11.' as LS_begDate
			,'01.12.' as LS_endDate
		union all
	select 13 as n
			,'Декабрь' as month_name
			,'01.12.' as LS_begDate
			,'01.01.' as LS_endDate
		union all
	select 14 as n
			,'За год' as month_name
			,'01.01.' as LS_begDate
			,'01.01.' as LS_endDate
	) b on true
 )
, LpSection as (
				select LpuP.Lpu_id
						,LS.LpuSection_id
						,LS.LpuSection_Code
						,LS.LpuSection_Name
						,LU.LpuUnitType_SysNick
						,LpuP.Lpu_begDate
						,LpuP.Lpu_endDate
						,LpuP.LS_begDate
						,LpuP.LS_endDate
						,LpuP.Stac_begDT
						,LpuP.Stac_endDT
						,LpuP.StacTime
						,ls.LpuSection_setDate as LpuSection_setDate
						,ls.LpuSection_disDate as LpuSection_disDate
						,LpuSectionAge_id
						,StrProf.LpuSectionBedProfile_id
				from param 
         inner join LpuP on true
				inner join dbo.v_LpuSection as LS on LS.Lpu_id = LpuP.Lpu_id
						and LS.LpuSectionProfile_SysNick = 'profil'
						and (LS.LpuBuilding_id = p_lpubuilding_id or p_lpubuilding_id is null)
						and (LS.LpuUnit_id = p_lpuunit_id or p_lpuunit_id is null)
						and (LS.LpuSection_id = p_lpusection_id or p_lpusection_id is null)
				inner join dbo.v_LpuUnit as LU on LU.LpuUnit_id = LS.LpuUnit_id
						and LU.LpuUnitType_SysNick in ('stac','dstac') 
						and (LU.LpuUnitType_id = p_lpuunittype_id or p_lpuunittype_id is null)
				inner join dbo.v_LpuBuilding as LB on LB.LpuBuilding_id = LU.LpuBuilding_id
						and (',' || coalesce(p_lpufiliallist, '') || ',' like '%,' || coalesce(cast(LB.LpuFilial_id as varchar), '0') || ',%' 
							or coalesce(rtrim(p_lpufiliallist), '') = '')
				inner join lateral (select -2 as LpuSectionBedProfile_id -- строка для всего отделения
									) as StrProf on true
			)
, Medservice_w as (
					select ms.MedService_id
							,ms.MedService_Code
							,ms.MedService_Name
							,LpuP.Lpu_id
							,LpuP.Stac_begDT
							,LpuP.Stac_endDT
							,LpuP.StacTime
							,ms.MedService_begDT
							,ms.MedService_endDT
					from param 
            inner join LpuP on true
			  		inner join dbo.v_MedService as ms on ms.Lpu_id = LpuP.Lpu_id
					where 1=1
					  and ms.MedServiceType_id = 67 --Службы реанимации
					)
, EvnPS_W as (
  select
    EvnPS.EvnPS_id, 
    EvnPS.EvnPS_setDate,
	EvnPS.EvnPS_disDate,
	EvnPS.EvnPS_setDT,
	EvnPS.EvnPS_disDT,
	EvnPS.Lpu_id,
	EvnPS.Person_id,
  EvnPS.Server_id,
	EvnPS.PersonEvn_id,
	EvnPS.Person_Age,
	EvnPS.LpuSection_id,
	EvnPS.LpuSection_pid,
	EvnPS.MedPersonal_pid,
	EvnPS.MedStaffFact_pid,
	EvnPS.PayType_id,
	EvnPS.Diag_id,
	EvnPS.Diag_pid,
	EvnPS.LeaveType_id,
    EvnPS.EvnPS_IsCont,
    EvnPS.PreHospType_id,
	EvnPS.PrehospDirect_id,
	EvnPS.LpuSection_did,
    EvnPS.PrehospArrive_id
  from v_EvnPS EvnPS 
	where EvnPS.PrehospWaifRefuseCause_id is null
			)
, EvnSection_w as (select
	ES.EvnSection_id, 
  coalesce(end_Reanim.EvnReanimatPeriod_disDT,ES.EvnSection_setDT) as EvnSection_setDT,
	coalesce(beg_Reanim.EvnReanimatPeriod_setDT,ES.EvnSection_disDT) as EvnSection_disDT,
	cast(cast(coalesce(end_Reanim.EvnReanimatPeriod_disDT,ES.EvnSection_setDT) as date) as timestamp) as EvnSection_setDate,
	cast(cast(coalesce(beg_Reanim.EvnReanimatPeriod_setDT,ES.EvnSection_disDT) as date) as timestamp) as EvnSection_disDate,
  ES.EvnSection_pid,
	ES.Lpu_id,
	ES.Server_id,
	ES.EvnSection_Index,
	ES.EvnSection_Count,
	case when beg_Reanim.EvnReanimatPeriod_setDT is not null then 1 else 0 end IsToRean,
	case when end_Reanim.EvnReanimatPeriod_disDT != ES.EvnSection_setDT then 1 else 0 end IsFromRean,
	ES.LpuSection_id as LpuSection_id,
	ES.PayType_id as PayType_id,
	ES.LeaveType_id as LeaveType_id,
	ES.EvnSection_IsPriem,
	ES.LpuSectionBedProfileLink_fedid,
	ES.EvnSection_IsAdultEscort,
	LSBPL.LpuSectionBedProfile_id

  from param inner join v_EvnSection ES on true
  left join fed.LpuSectionBedProfileLink LSBPL  on LSBPL.LpuSectionBedProfileLink_id = ES.LpuSectionBedProfileLink_fedid
   left join lateral
  (select ES.EvnSection_setDT as EvnReanimatPeriod_disDT
  union all
   select 
     erp.EvnReanimatPeriod_disDT
   from v_EvnReanimatPeriod erp  
   where 1=1
     and ES.EvnSection_id = erp.EvnReanimatPeriod_pid
     and erp.EvnReanimatPeriod_disDT is not null
  	 and erp.ReanimResultType_id = 1
     and param.p_NeedReanim is null  
  ) end_Reanim on true
  left join lateral
  (select 
     rp.EvnReanimatPeriod_setDT
   from v_EvnReanimatPeriod rp 
   where 1=1
     and ES.EvnSection_id = rp.EvnReanimatPeriod_pid
     and rp.EvnReanimatPeriod_setDT>=end_Reanim.EvnReanimatPeriod_disDT
     and p_NeedReanim is null 
   order by rp.EvnReanimatPeriod_setDT limit 1
  ) beg_Reanim on true
  ),
EvnSectionRean_w as (
select
	erp.Evn_id as EvnSection_id, 
  erp.Evn_setDT as EvnSection_setDT,
	erp.Evn_disDT as EvnSection_disDT,
	cast(cast(erp.Evn_setDT as date) as timestamp) as EvnSection_setDate,
	cast(cast(erp.Evn_disDT as date) as timestamp) as EvnSection_disDate,
    erp.Evn_pid as EvnSection_pid,
    erp.Evn_rid as EvnSection_rid,
	erp.Lpu_id as Lpu_id,
	erp.Server_id as Server_id,
	erp.Person_id,
	erp.Evn_Index as EvnSection_Index,
	erp.Evn_Count as EvnSection_Count,
	erp.ReanimResultType_id,
	erp.LpuSectionBedProfile_id,
	erp.MedService_id,
	erp.LpuSection_id
from param inner join EvnReanimatPeriod erp on true
where 1 = 1
  and erp.Evn_deleted = 1
  and coalesce(p_NeedReanim,2) = 2 
)
,EPS as (
		select mn.n
			,COUNT(distinct case when ES.EvnSection_setDT < dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and (ES.EvnSection_disDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT) or ES.EvnSection_disDT is null)
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then EPS.EvnPS_id end) as val6
			,COUNT(case when ES.EvnSection_setDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_setDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ESPriem.EvnSection_id is null
									and ES.IsFromRean = 0 --Не переведен из реанимации
									and (coalesce(EPS.EvnPS_IsCont, 1) = 1 or EPS.EvnPS_IsCont = 2 and coalesce(EPS.PrehospDirect_id, -1) <> 1) -- кроме "Кем направлен" = "Отделение МО"
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val7
			,COUNT(case when ES.EvnSection_setDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_setDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ESPriem.EvnSection_id is null 
									and ES.IsFromRean = 0 --Не переведен из реанимации
									and (coalesce(EPS.EvnPS_IsCont, 1) = 1 or EPS.EvnPS_IsCont = 2 and coalesce(EPS.PrehospDirect_id, -1) <> 1) -- кроме "Кем направлен" = "Отделение МО"
									and prevStac.EvnPS_id is not null
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val8
			,COUNT(case when ES.EvnSection_setDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_setDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ESPriem.EvnSection_id is null 
									and ES.IsFromRean = 0 --Не переведен из реанимации
									and (coalesce(EPS.EvnPS_IsCont, 1) = 1 or EPS.EvnPS_IsCont = 2 and coalesce(EPS.PrehospDirect_id, -1) <> 1) -- кроме "Кем направлен" = "Отделение МО"
									and Addr.KLAreaType_id = 2
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val9
			,COUNT(case when ES.EvnSection_setDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_setDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ESPriem.EvnSection_id is null 
									and ES.IsFromRean = 0 --Не переведен из реанимации
									and (coalesce(EPS.EvnPS_IsCont, 1) = 1 or EPS.EvnPS_IsCont = 2 and coalesce(EPS.PrehospDirect_id, -1) <> 1) -- кроме "Кем направлен" = "Отделение МО"
									and dbo."ageymd"(PS.Person_BirthDay, EPS.EvnPS_setDate, 1) < 18
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val10
			,COUNT(case when ES.EvnSection_setDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_setDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ESPriem.EvnSection_id is null 
									and ES.IsFromRean = 0 --Не переведен из реанимации
									and (coalesce(EPS.EvnPS_IsCont, 1) = 1 or EPS.EvnPS_IsCont = 2 and coalesce(EPS.PrehospDirect_id, -1) <> 1) -- кроме "Кем направлен" = "Отделение МО"
									and dbo."ageymd"(PS.Person_BirthDay, EPS.EvnPS_setDate, 1) >= 60
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val11
			,COUNT(case when ES.EvnSection_setDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_setDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and (ESPriem.EvnSection_id is not null
										or ES.IsFromRean = 1 --Переведен из реанимации
										or EPS.EvnPS_IsCont = 2 and EPS.PrehospDirect_id = 1 and ESPriem.EvnSection_id is null)
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val12
			, COUNT(case when ES.EvnSection_disDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_disDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and (ES.EvnSection_Index = ES.EvnSection_Count - 1 and LT.LeaveType_SysNick in ('section','ksper','dsper','psreab')
										or ES.IsToRean = 1 --Переведен в реанимацию
										or ES.EvnSection_Index < ES.EvnSection_Count - 1)
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val13
			,COUNT(case when ES.EvnSection_disDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_disDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ES.EvnSection_Index = ES.EvnSection_Count - 1   
									and ES.IsToRean = 0 --Не переведен в реанимацию
									and LT.LeaveType_Code is not null
                  and coalesce(flt.LeaveType_Code, 0) not in (105,106,205,206)
                  and coalesce(LT.LeaveType_SysNick, '') not in ('section','ksper','dsper','psreab')
									and coalesce(RD.ResultDesease_SysNick, '') != 'umer'
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val14
			,COUNT(case when ES.EvnSection_disDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_disDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ES.EvnSection_Index = ES.EvnSection_Count - 1
									and ES.IsToRean = 0 --Не переведен в реанимацию
									and (coalesce(LT.LeaveType_SysNick, '') = 'stac' and coalesce(LUTOSt.LpuUnitType_SysNick,'') in ('','dstac','pstac')
										or coalesce(LT.LeaveType_SysNick, '') in ('ksstac','dstac','psdomstac','psdstac'))
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val15
			,COUNT(case when ES.EvnSection_disDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_disDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ES.EvnSection_Index = ES.EvnSection_Count - 1
									and ES.IsToRean = 0 --Не переведен в реанимацию
									and (coalesce(LT.LeaveType_SysNick, '') = 'stac' and LUTOSt.LpuUnitType_SysNick = 'stac'
										or coalesce(LT.LeaveType_SysNick, '') in ('kstac','dsstac'))
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val16
			,COUNT(case when ES.EvnSection_disDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_disDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ES.EvnSection_Index = ES.EvnSection_Count - 1
									and ES.IsToRean = 0 --Не переведен в реанимацию
									and coalesce(LT.LeaveType_SysNick, '') in ('other','ksother','dsother','ksperitar')
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate 
							then ES.EvnSection_id end) as val17
			,COUNT(case when ES.EvnSection_disDT >= dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)
									and ES.EvnSection_disDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT)
									and ES.EvnSection_Index = ES.EvnSection_Count - 1
									and ES.IsToRean = 0 --Не переведен в реанимацию
                  and (coalesce(flt.LeaveType_Code, 0) in (105,106,205,206) or RD.ResultDesease_SysNick = 'umer')
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then ES.EvnSection_id end) as val18
			,COUNT(distinct case when EvnSection_setDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) 
									and (ES.EvnSection_disDT >= dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) or ES.EvnSection_disDT is null)
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
							then EPS.EvnPS_id end) as val19
			,coalesce(SUM(case when ES.EvnSection_setDT is not null 
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
									and (ES.EvnSection_setDT != ES.EvnSection_disDT or ES.EvnSection_disDT is null)
							then cast(dbo."mindate"(coalesce(ES.EvnSection_disDate, dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) - INTERVAL '1 minute'),dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) - INTERVAL '1 minute') as date)
									- cast(dbo."maxdate"(ES.EvnSection_setDate, cast(dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT) as date)) as date) 
									 
									+ case when cast(dbo."maxdate"(ES.EvnSection_setDT, dbo."maxdate"(dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT),ls.Stac_begDT)) as time) < LS.StacTime
										then 1 else 0 end
									+ case when cast(dbo."mindate"(coalesce(ES.EvnSection_disDT, dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) - INTERVAL '1 minute')
																	, dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) - INTERVAL '1 minute' ) as time) >= LS.StacTime
										then 1 else 0 end
									+ case when LS.LpuUnitType_SysNick = 'stac'	and ES.EvnSection_disDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) -- выписка в отчетный период
										then case when cast(ES.EvnSection_setDate as date) - cast(ES.EvnSection_disDate as date) 
														+ case when cast(ES.EvnSection_setDT as time) < LS.StacTime then 1 else 0 end 
														+ case when cast(ES.EvnSection_disDT as time) >= LS.StacTime then 1 else 0 end  > 1 
											then -1 else 0 end 
										else 0 end 
							else 0 end), 0
						) as val20
			,coalesce(SUM(case when ES.EvnSection_setDT is not null 
									and mn.LS_begDate <= ls.LS_endDate
									and mn.LS_endDate >= ls.LS_begDate
									and (ES.EvnSection_setDT != ES.EvnSection_disDT or ES.EvnSection_disDT is null)
									and EvnSection_IsAdultEscort = 2 
							then cast(dbo."mindate"(coalesce(ES.EvnSection_disDate, dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) - INTERVAL '1 minute'),dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) - INTERVAL '1 minute') as date)
									- cast(dbo."maxdate"(ES.EvnSection_setDate, cast(mn.Stac_begDT as date)) as date)
									+ case when cast(dbo."maxdate"(ES.EvnSection_setDT, dbo."maxdate"(mn.Stac_begDT,ls.Stac_begDT)) as time) < LS.StacTime
										then 1 else 0 end
									+ case when cast(dbo."mindate"(coalesce(ES.EvnSection_disDT, dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) - INTERVAL '1 minute')
																	,dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) - INTERVAL '1 minute') as time) >= LS.StacTime
										then 1 else 0 end
									+ case when LS.LpuUnitType_SysNick = 'stac' and ES.EvnSection_disDT < dbo."mindate"(mn.Stac_endDT,ls.Stac_endDT) -- выписка в отчетный период
										then case when cast(ES.EvnSection_setDate as date) - cast(ES.EvnSection_disDate as date)
														+ case when cast(ES.EvnSection_setDT as time) < LS.StacTime then 1 else 0 end
														+ case when cast(ES.EvnSection_disDT as time) >= LS.StacTime then 1 else 0 end > 1
											then -1 else 0 end
										else 0 end
							else 0 end), 0
						) as val22
from param inner join LpSection as LS on true
inner join EvnSection_w as ES on ES.LpuSection_id = LS.LpuSection_id
							and ES.Lpu_id = LS.Lpu_id
							and (ES.EvnSection_disDT >= LS.Stac_begDT or ES.EvnSection_disDT is null) 
							and EvnSection_setDT < LS.Stac_endDT 
							and coalesce(ES.EvnSection_IsPriem, 1) = 1
							and (ES.LpuSectionBedProfile_id = LS.LpuSectionBedProfile_id or LS.LpuSectionBedProfile_id = -2)
							and (ES.PayType_id = p_paytype_id or p_paytype_id is null)
right join lp_month as mn on (ES.EvnSection_disDT >= mn.Stac_begDT or ES.EvnSection_disDT is null) and EvnSection_setDT < mn.Stac_endDT
inner join EvnPS_W as EPS on EPS.EvnPS_id = ES.EvnSection_pid
inner join dbo.v_Person_all as PS on PS.PersonEvn_id = EPS.PersonEvn_id 
				and EPS.Server_id = PS.Server_id
left join v_PersonNationalityStatus PNS on PS.PersonEvn_id = PNS.PersonNationalityStatus_id and PS.Server_id = PNS.Server_id

left join v_LeaveType LT  on LT.LeaveType_id = ES.LeaveType_id
left join fed.LeaveType flt on lt.LeaveType_fedid = flt.LeaveType_id
 LEFT JOIN LATERAL (select
               eps1.EvnPS_id
             from v_evnPS eps1
               inner join v_EvnSection es1 on eps1.EvnPS_id = es1.EvnSection_pid
                     and es1.EvnSection_Index = es1.EvnSection_Count -1
               inner join v_LpuSection LS1 on es1.LpuSection_id = LS1.LpuSection_id
               inner join v_LpuUnit LUDir on LUDir.LpuUnit_id = LS1.LpuUnit_id 
            where eps1.Person_id = EPS.Person_id
              and eps1.Lpu_id = EPS.Lpu_id
            	and eps1.EvnPS_disDate = eps.EvnPS_setDate
            	and LUDir.LpuUnitType_SysNick  in ('dstac','pstac')
          limit 1  	
         ) prevStac on true
left join dbo.Address as Addr on Addr.Address_id = coalesce(PS.PAddress_id, PS.UAddress_id)
left join dbo.v_EvnOtherStac as EOSt on EOSt.EvnOtherStac_pid = ES.EvnSection_id
left join dbo.v_LpuUnitType as LUTOSt on LUTOSt.LpuUnitType_id = EOSt.LpuUnitType_oid
left join dbo.v_EvnLeaveBase as ELB on ELB.EvnLeaveBase_pid = ES.EvnSection_id
left join dbo.v_ResultDesease as rd on ELB.ResultDesease_id = rd.ResultDesease_id

left join lateral (select ESPriem.EvnSection_id
					from dbo.v_EvnSection as ESPriem 
					where 1 = 1
					  and ESPriem.EvnSection_pid = ES.EvnSection_pid
					  and ESPriem.EvnSection_Index = ES.EvnSection_Index-1  
					  and coalesce(ESPriem.EvnSection_IsPriem,1) = 1
					) as ESPriem on true
where (param.p_national is null or (COALESCE(PNS.KLCountry_id,643) = 643 and param.p_national = 1) or (COALESCE(PNS.KLCountry_id,643) != 643 and param.p_national = 2))
  and coalesce(p_NeedReanim,1) = 1 
group by mn.n
),
EPS_rean as (
select
  mn.n,
  --Состояло больных на начало истекших суток
  COUNT(distinct case when ES.EvnSection_setDT < dbo.Maxdate(mn.Stac_begDT,ls.Stac_begDT)
    and (ES.EvnSection_disDT >= dbo.Maxdate(mn.Stac_begDT,ls.Stac_begDT)
      or ES.EvnSection_disDT is null)
	and mn.LS_begDate<=ls.LS_endDate
	and mn.LS_endDate>=ls.LS_begDate
    then ES.Person_id end) as val6,
   --переведено больных внутри больницы из других отделений
   COUNT( case when ES.EvnSection_setDT >= dbo.Maxdate(mn.Stac_begDT,ls.Stac_begDT)
    and ES.EvnSection_setDT < dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT)
	and mn.LS_begDate<=ls.LS_endDate
	and mn.LS_endDate>=ls.LS_begDate
    then ES.EvnSection_id end) as val12,
   --переведено больных внутри больницы в другие отделения
   COUNT( case when ES.EvnSection_disDT >= dbo.Maxdate(mn.Stac_begDT,ls.Stac_begDT)
    and ES.EvnSection_disDT < dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT)
	and ES.ReanimResultType_id in (1,4)
	and mn.LS_begDate<=ls.LS_endDate
	and mn.LS_endDate>=ls.LS_begDate
    then ES.EvnSection_id end) as val13,
  --умерло
  COUNT( case when ES.EvnSection_disDT >= dbo.Maxdate(mn.Stac_begDT,ls.Stac_begDT)
    and ES.EvnSection_disDT < dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT)
	and ES.ReanimResultType_id in (2,3)
	and mn.LS_begDate<=ls.LS_endDate
	and mn.LS_endDate>=ls.LS_begDate
    then EPS.EvnPS_id end) as val18,
  --На начало текущего дня  состоит больных - всего
  COUNT(distinct case when EvnSection_setDT < dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT)
    and (ES.EvnSection_disDT >= dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT)
      or ES.EvnSection_disDT is null)
	and mn.LS_begDate<=ls.LS_endDate
	and mn.LS_endDate>=ls.LS_begDate
    then ES.Person_id end) as val19,

  coalesce(SUM(case when ES.EvnSection_setDT is not null 
	and mn.LS_begDate<=ls.LS_endDate
	and mn.LS_endDate>=ls.LS_begDate
  then DATEDIFF('day', dbo.MaxDate(ES.EvnSection_setDate, cast(dbo.Maxdate(mn.Stac_begDT,ls.Stac_begDT) as date)), 
      dbo.MinDate(coalesce(ES.EvnSection_disDate, cast(dateadd('minute', -1, dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT)) as date)), cast(dateadd('minute', -1, dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT)) as date))) +
   
    case when cast(dbo.MaxDate(ES.EvnSection_setDT, mn.Stac_begDT) as time) < ls.StacTime
      then 1 else 0 end +
         
    case when cast(dbo.MinDate(coalesce(ES.EvnSection_disDT, dateadd('minute', -1, dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT))), dateadd('minute', -1, dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT))) as time) >= ls.StacTime
      then 1 else 0 end +
         
    case when LS.LpuUnitType_SysNick = 'stac'
      and ES.EvnSection_disDT < dbo.MinDate(mn.Stac_endDT,ls.Stac_endDT) -- выписка в отчетный период
    then case when DATEDIFF('day', ES.EvnSection_setDate, ES.EvnSection_disDate) + 
           case when cast(ES.EvnSection_setDT as time) < ls.StacTime then 1 else 0 end +
           case when cast(ES.EvnSection_disDT as time) >= ls.StacTime then 1 else 0 end > 1
           then -1 else 0 end
    else 0 end
  else 0 end), 0) as val20 

from param inner join LpSection LS on true
  inner join EvnSectionRean_w ES  on ES.LpuSection_id = LS.LpuSection_id and LS.LpuSectionBedProfile_id = -2
  and LS.Lpu_id = es.Lpu_id
  and (ES.EvnSection_disDT >= LS.Stac_begDT or ES.EvnSection_disDT is null) 
  and EvnSection_setDT < LS.Stac_endDT
  inner join EvnPS_W EPS on EPS.EvnPS_id = ES.EvnSection_rid
    and EPS.EvnPS_setDT < LS.Stac_endDT
    and coalesce(EPS.EvnPS_disDT, LS.Stac_begDT) >= LS.Stac_begDT
   right join lp_month mn on (ES.EvnSection_disDT >= mn.Stac_begDT or ES.EvnSection_disDT is null)  and EvnSection_setDT < mn.Stac_endDT
  inner join v_Person_all PS on PS.PersonEvn_id = EPS.PersonEvn_id 
				and EPS.Server_id = PS.Server_id
  left join v_PersonNationalityStatus PNS on PS.PersonEvn_id = PNS.PersonNationalityStatus_id and PS.Server_id = PNS.Server_id
  left join lateral (
    select -2 as LpuSectionBedProfile_id
  ) LSBP on true
where (param.p_national is null or (COALESCE(PNS.KLCountry_id,643) = 643 and param.p_national = 1) or (COALESCE(PNS.KLCountry_id,643) != 643 and param.p_national = 2))
  and coalesce(p_NeedReanim,2) = 2 
group by  mn.n
)
select distinct 0 as "TypeR"
				,mn.n
				,cast(mn.month_name as varchar) as month_name
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(LSBS.BedState_Fact, 0) end as val3
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(LSW.BedState_Repair, 0) end as val4
				,case when coalesce(p_NeedReanim,1)=1 then cast(ROUND((1.0 * coalesce(KoikiSred, 0)) / case when dbo."ageymd"(mn.LS_begDate, mn.LS_endDate, 3) = 0 then 1 else dbo."ageymd"(mn.LS_begDate, mn.LS_endDate, 3) end , 0) as int) end as val5
				,coalesce(EPS.val6, 0) + coalesce(EPS_rean.val6, 0) as val6
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val7, 0) end as val7
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val8, 0) end as val8
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val9, 0) end as val9
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val10, 0) end as val10
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val11, 0) end as val11
				,coalesce(EPS.val12, 0)+ coalesce(EPS_rean.val12, 0) as val12
				,coalesce(EPS.val13, 0)+ coalesce(EPS_rean.val13, 0) as val13
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val14, 0) end as val14
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val15, 0) end as val15
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val16, 0) end as val16
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val17, 0) end as val17
				,coalesce(EPS.val18, 0) + coalesce(EPS_rean.val18, 0) as val18
				,coalesce(EPS.val19, 0) + coalesce(EPS_rean.val19, 0) as val19
				,coalesce(EPS.val20, 0) + coalesce(EPS_rean.val20, 0) as val20
				,case when coalesce(p_NeedReanim,1)=1 then coalesce(EPS.val22, 0) end as val22


from param inner join lp_month as mn on true
left join EPS on EPS.n = mn.n
left join EPS_rean on EPS_rean.n = mn.n
left join lateral (select SUM(LpuSectionBedState_Fact) as BedState_Fact
			from dbo.v_LpuSectionBedState as LSBS
			join LpSection as ls on ls.LpuSection_id= LSBS.LpuSection_id
			left join fed.LpuSectionBedProfileLink as LSBPL on LSBPL.LpuSectionBedProfileLink_id = LSBS.LpuSectionBedProfileLink_fedid
			where 1=1
			  and (LS.LpuSection_setDate <= dbo."mindate"(mn.LS_endDate,ls.LS_endDate) or LS.LpuSection_setDate is null)
			  and (LS.LpuSection_disDate >= dbo."mindate"(mn.LS_endDate,ls.LS_endDate) or LS.LpuSection_disDate is null)  
			  and cast(LpuSectionBedState_begDate as date) <= dbo."mindate"(mn.LS_endDate,ls.LS_endDate)
			  and (cast(LpuSectionBedState_endDate as date) >= dbo."mindate"(mn.LS_endDate,ls.LS_endDate) or LpuSectionBedState_endDate is null)  
			  and LS.Lpu_begDate <= mn.LS_endDate
			  and coalesce(LS.Lpu_endDate, ls.LS_endDate) >= dbo."mindate"(mn.LS_endDate,ls.LS_endDate)
			  and (LSBPL.LpuSectionBedProfile_id = p_lpusectionbedprofile_id or p_lpusectionbedprofile_id is null)
			  and mn.LS_begDate <= ls.LS_endDate
			  and mn.LS_endDate >= ls.LS_begDate
			) as LSBS on true
left join lateral (select sum(LpuSectionWard_BedRepair) as BedState_Repair --койки на ремонте
					,sum(case when LSW.Sex_id = 1 then (LpuSectionWard_BedCount - LpuSectionWard_BedRepair) else 0 end) as male --мужские койки
					,sum(case when LSW.Sex_id = 2 then (LpuSectionWard_BedCount - LpuSectionWard_BedRepair) else 0 end) as female --женские койки
			from dbo.v_LpuSectionWard as LSW
			join LpSection as ls on ls.LpuSection_id= LSw.LpuSection_id
			where 1=1
			  and (LS.LpuSection_setDate <= dbo."mindate"(mn.LS_endDate,ls.LS_endDate) or LS.LpuSection_setDate is null)
			  and (LS.LpuSection_disDate >= dbo."mindate"(mn.LS_endDate,ls.LS_endDate) or LS.LpuSection_disDate is null)  
			  and cast(LpuSectionWard_setDate as date) <= dbo."mindate"(mn.LS_endDate,ls.LS_endDate)
			  and (cast(LpuSectionWard_disDate as date) >= dbo."mindate"(mn.LS_endDate,ls.LS_endDate) or LpuSectionWard_disDate is null)
			  and LS.Lpu_begDate <= LS.LS_endDate
			  and coalesce(LS.Lpu_endDate, LS.LS_endDate) >= dbo."mindate"(mn.LS_endDate,ls.LS_endDate)
			  and mn.LS_begDate <= ls.LS_endDate
			  and mn.LS_endDate >= ls.LS_begDate
			) as LSW on true
left join lateral (select SUM(LpuSectionBedState_Fact * dbo.AgeYMD(dbo."maxdate"(LSDate.LS_begDate, cast(LpuSectionBedState_begDate as date))
					,dbo."maxdate"(cast(coalesce(LpuSectionBedState_endDate, LSDate.LS_endDate) as date), LSDate.LS_endDate), 3)) as KoikiSred
			from dbo.v_LpuSectionBedState as LSBS
			join LpSection as ls on ls.LpuSection_id= LSBS.LpuSection_id
			left join fed.LpuSectionBedProfileLink as LSBPL on LSBPL.LpuSectionBedProfileLink_id = LSBS.LpuSectionBedProfileLink_fedid
			left join lateral (select mn.LS_begDate, mn.LS_endDate
								) as LSDate on true
			where 1=1
			  and mn.LS_begDate <= ls.LS_endDate
			  and mn.LS_endDate >= ls.LS_begDate
			  and (LS.LpuSection_setDate <= dbo."mindate"(mn.LS_endDate,ls.LS_endDate) or LS.LpuSection_setDate is null)
			  and (LS.LpuSection_disDate >= mn.LS_begDate or LS.LpuSection_disDate is null)  
			  and cast(LpuSectionBedState_begDate as date) <= dbo."mindate"(mn.LS_endDate,ls.LS_endDate)
			  and (cast(LpuSectionBedState_endDate as date) >= mn.LS_begDate or LpuSectionBedState_endDate is null)  
			  and LS.Lpu_begDate <= LS.LS_endDate
			  and coalesce(LS.Lpu_endDate, LS.LS_endDate) >= dbo."mindate"(mn.LS_endDate,ls.LS_endDate)
			  and (LSBPL.LpuSectionBedProfile_id = p_lpusectionbedprofile_id or p_lpusectionbedprofile_id is null)
			) as KoikiSred on true
where 1 = 1
order by n
