with params as(
	select
		cast($1 as bigint) as p_report_id,
		cast($2 as bigint) as p_user_id, -- 345292321080 ВРАЧ2 ТЕСТ swnt_adyg
		cast($3 as timestamp) as p_begdate,
		cast($4 as timestamp) as p_enddate
),

tempres as
(
SELECT  --TOP 100 
	ReportRun_id,
	rr.Report_id, 
	r.Report_Title as Report_Name, 
	--Report_Params,
	--r.Region_id,
	rr.pmUser_insID,
	pmuser.Lpu_id,
	pmuser.pmUser_name,
	rr.ReportRun_insDT,
	coalesce(cast(ReportRun_begDT as date), cast(ReportRun_queueDT as date)) as report_date,
	--cast(ReportRun_begDT as date) as report_date,
	ReportRun_queueDT	,
	--isnull(convert(varchar(10), cast(ReportRun_begDT as datetime), 104),convert(varchar(10), cast(ReportRun_queueDT as datetime), 104)) as report_date,
--	isnull(convert(varchar(10), cast(ReportRun_begDT as datetime), 102),convert(varchar(10), cast(ReportRun_queueDT as datetime), 102)) as date_report,
--	convert(varchar(10), cast(ReportRun_queueDT as datetime), 104) + ' ' + convert(varchar(5), cast(ReportRun_queueDT as datetime), 108) as ReportRun_queueDT,
--	convert(varchar(10), cast(ReportRun_begDT as datetime), 104) + ' ' + convert(varchar(5), cast(ReportRun_begDT as datetime), 108) as ReportRun_begDT,
--	convert(varchar(10), cast(ReportRun_endDT as datetime), 104) + ' ' + convert(varchar(5), cast(ReportRun_endDT as datetime), 108) as ReportRun_endDT,
	ReportRun_Status,
	case
		when ReportRun_Status = 1 then 'Сформирован' else 'Не сформирован'
	end as ReportRun_StatusName,

--	'export/reports/'::text || ReportRun_FilePath as ReportRun_FilePath,
--	ReportRun_Format,
--	case when p_report_id is not null /*and ReportRun_Status != 1*/ then r.report_position end as report_position,
	null as report_position,
	pmusers.pmUser_name as pmUser_signName,
	rr.ReportRun_IsSigned
--	convert(varchar(10), rr.ReportRun_signDT, 104) as ReportRun_signDT
FROM params
	inner join rpt.v_ReportRun rr on true
	left join rpt.v_Report r on rr.Report_id = r.Report_id
	left join v_pmUser pmuser on pmuser.pmUser_id = rr.pmUser_insID
	left join v_pmUser pmusers on pmusers.pmUser_id = rr.pmUser_signID
WHERE (1=1) 
	and (rr.Report_id = p_report_id or p_report_id is null)
	and 
	(
		(rr.pmUser_insID =  p_user_id or p_user_id is null)
		or
		(rr.pmUser_signID = p_user_id or p_user_id is null)
	)
	and cast(rr.ReportRun_insDT as date) between p_begdate and p_enddate
	--and cast(rr.ReportRun_insDT as date) <= @EndDate
)			

--select * from tempres


select --* 
	to_char(report_date, 'dd.mm.yyyy') as v1_date,
	--date_report,
	count(Report_id) as v2_count,
	count(case when ReportRun_queueDT is not null then Report_id end) as v3_queue,
	count(case when ReportRun_status = 1 then Report_id end) as v4_end,
	count(case when ReportRun_status = 1 and ReportRun_queueDT is not null then Report_id end) as v5_queue,
	count(case when ReportRun_queueDT is not null then Report_id end) as v6_queue,
	report_position as v7_position
from tempres
group by report_date, report_position	
order by report_date		

