with params as
(
	select
		cast($1 as bigint) as p_lpu_id,
		cast($2 as bigint) as p_lpubuilding_id,
		cast($3 as bigint) as p_lpuunit_id,
		cast($4 as bigint) as p_lpusection_id,
		cast($5 as bigint) as p_medpersonal_id,
		cast($6 as bigint) as p_paytype_id,
		cast($7 as bigint) as p_yesno_id,
		cast($8 as bigint) as p_uslugacomplex_id,
		cast($9 as timestamp) as p_begdate,
		cast($10 as timestamp) as p_enddate
)

select 
	LpuSection.Lpu_Name as "Lpu_Name",
	lpuUnit.LpuBuilding_Name as "LpuBuilding_Name",
	lpuUnit.LpuUnit_Name as "LpuUnit_Name",
	LpuSection.LpuSection_Name as "LpuSection_Name",
	MP.Person_Fio as "MedPersonal_fio",
	UC.UslugaComplex_Code as "UslugaComplex_Code",
	UC.UslugaComplex_Name as "UslugaComplex_Name",
	--count(*) AS countt,
	--SUM(cast(EVPL.EvnVizitPLStom_Uet as money)) AS EvnUslugaStom_UED
	SUM(EvnUslugaStom_kolvo) AS countt,
	SUM(EUS.EvnUslugaStom_summa) AS "EvnUslugaStom_UED" --#166780

from params
	inner join v_EvnUslugaStom AS EUS on true
	inner join v_EvnVizitPLStom AS EVPL on EUS.EvnUslugaStom_pid = EVPL.EvnVizitPLStom_id
	inner join v_EvnPLStom AS EPS on EVPL.EvnVizitPLStom_pid = EPS.EvnPLStom_id
	inner join v_MedPersonal AS MP on EVPL.MedPersonal_id = MP.MedPersonal_id and EVPL.Lpu_id = MP.Lpu_id
	inner join v_LpuSection AS LpuSection on LpuSection.LpuSection_id = EVPL.LpuSection_id
	inner join v_LpuUnit AS LpuUnit on LpuUnit.LpuUnit_id = LpuSection.LpuUnit_id
	inner join v_UslugaComplex AS UC on EUS.UslugaComplex_id = UC.UslugaComplex_id
where (1=1)
	and (EVPL.Lpu_id = p_lpu_id or p_lpu_id is null) 
	and (lpuUnit.lpuBuilding_id = p_lpubuilding_id or p_lpubuilding_id is null) 
	and (lpuUnit.lpuUnit_id = p_lpuunit_id or p_lpuunit_id is null) 
	and (EVPL.LpuSection_id = p_lpusection_id or p_lpusection_id is null)
	and (EVPL.MedPersonal_id = p_medpersonal_id or p_medpersonal_id is null)
	and (EVPL.PayType_id = p_paytype_id or p_paytype_id is null) 
	and (EPS.EvnPLStom_IsFinish = p_yesno_id or p_yesno_id is null)
            --and (EUS.EvnUslugaStom_setDate between stom_reference_on_services_pg.begdate and stom_reference_on_services_pg.enddate)
	and (EUS.USlugaComplex_id = p_uslugacomplex_id or p_uslugacomplex_id is null)
	and (EVPL.EvnVizitPLStom_setdate between p_begdate and p_enddate) --#166780

group by 
	LpuSection.Lpu_Name,
	lpuUnit.LpuBuilding_Name,
	lpuUnit.LpuUnit_Name,
	LpuSection.LpuSection_Name,
	MP.Person_Fio,
	UC.UslugaComplex_Code,
	UC.UslugaComplex_Name
