SELECT 
	d.Diag_SCode Diag_Code
FROM (
	SELECT es.EvnVizitPL_id Evn_id, row_number() over(order by Evn.Evn_setDT desc, Evn.Evn_insDT desc) rn
	FROM dbo.v_EvnVizitPL es  
	JOIN v_Evn Evn   ON Evn.Evn_id = es.EvnVizitPL_id and Evn.Evn_pid = $1
	UNION 
	SELECT es.EvnSection_id, row_number() over(order by case when es.EvnSection_IsPriem = 2 then 1 else 0 end, Evn.Evn_setDT desc, Evn.Evn_insDT desc)
	FROM dbo.v_EvnSection es  
	JOIN v_Evn Evn   ON Evn.Evn_id = es.EvnSection_id and Evn.Evn_pid = $2
) l
JOIN dbo.v_Evn Evn   ON Evn.Evn_pid = l.Evn_id
JOIN dbo.v_EvnDiag EvnDiag    ON Evn.Evn_id = EvnDiag.EvnDiag_id 
JOIN dbo.v_Diag d   ON d.Diag_id = EvnDiag.Diag_id
WHERE  d.Diag_SCode  IN  ('Z03.8','Z11.5','Z20.8','Z22.8','U07.1','U07.2','J12.0','J12.1','J12.2','J12.3','J12.8','J12.9',
'J13', 'J14', 'J15.0', 'J15.1', 'J15.2', 'J15.3', 'J15.4', 'J15.5', 'J15.6', 'J15.7', 'J15.8', 'J15.9', 'J16.0', 'J16.8', 'J17.0', 
'J17.1','J17.2','J17.3', 'J17.8', 'J18.0', 'J18.1', 'J18.2', 'J18.8', 'J18.9')
