SELECT
	'prod-conc-50327-rmis'/*из конфига*/ AS Rmis_Id,
	TimeTableHistory.TimeTableGrafHist_id AS Book_Id_Rmis,
	TimeTableHistory.TimeTableGraf_begTime AS Visit_Time,
	'SUCCESS' AS Status_id,
	MedStaffFact.LpuUnit_id AS MO_Id,
	coalesce (LpuUnit_FRMOUnitID,FRMOUnit.FRMOUnit_OID,FRMOSection.FRMOUnit_OID, Token.PassportToken_tid) AS MO_OID,
	CASE WHEN LpuUnit_FRMOid IS NOT NULL THEN PassportToken_ShortName  ||', '|| lpuunit.LpuUnit_Name
	ELSE PassportToken_ShortName ||', '|| coalesce(FRMOUnit.FRMOUnit_Name,FRMOSection.FRMOUnit_Name) END AS MO_Name,
    Post.Post_Code AS ServiceSpec_Id,
	Post.Post_Name AS ServiceSpec_Name,
    coalesce(MedStaffFact.Person_Snils,'00000000000') ||'.'|| MedStaffFact.MedStaffFact_id::VARCHAR(20) AS Resource_Id,
    Person_Fio AS Resource_Name,
	 
			coalesce(RecMethodType.RecMethodType_FedCode,'REG') AS Code_id 
		 
	FROM TimeTableGrafHist TimeTableHistory  
    INNER JOIN dbo.v_TimeTableGraf ttg ON TimeTableHistory.TimeTableGraf_id = ttg.TimeTableGraf_id
    INNER JOIN dbo.v_EvnDirection_all ed ON ttg.EvnDirection_id = ed.EvnDirection_id and ed.EvnStatus_id = 15 and ed.EvnDirection_statusDate between $1 and $2
	INNER JOIN v_MedStaffFact MedStaffFact   on TimeTableHistory.MedStaffFact_id = MedStaffFact.MedStaffFact_id
	INNER JOIN dbo.v_lpuunit lpuunit   ON lpuunit.Lpuunit_id = MedStaffFact.Lpuunit_id
	INNER JOIN nsi.v_PostLink PostLink on MedStaffFact.Post_id = PostLink.Post_lid
	INNER JOIN nsi.v_Post Post on PostLink.Post_id = Post.Post_id

	LEFT JOIN dbo.RecMethodType  ON RecMethodType.RecMethodType_id = TimeTableHistory.RecMethodType_id
	LEFT JOIN nsi.FRMOUnit  ON FRMOUnit.FRMOUnit_id = LpuUnit.FRMOUnit_id
	LEFT JOIN LATERAL (
	    SELECT FRMOSection.FRMOUnit_OID, FRMOUnit_Name FROM dbo.v_LpuSection
		INNER JOIN nsi.FRMOSection ON FRMOSection.FRMOSection_id = v_LpuSection.FRMOSection_id
		INNER JOIN nsi.FRMOUnit ON FRMOUnit.FRMOUnit_OID = FRMOSection.FRMOUnit_OID
		WHERE FRMOSection.FRMOUnit_OID IS NOT NULL
			AND v_LpuSection.LpuUnit_id=lpuunit.LpuUnit_id limit 1
	) AS FRMOSection on true
	LEFT JOIN fed.v_PassportToken Token   ON Token.Lpu_id = LpuUnit.Lpu_id
	WHERE (1 = 1)
		AND TimeTableHistory.TimeTableGrafAction_id IN (2)
		AND TimeTableHistory.TimeTableGraf_begTime::date > (getdate()- interval '30 day')::date
		 
				AND TimeTableHistory.pmUser_updID != 999900
			 
		AND TimeTableHistory.TimeTableType_id in (1,2,4,9,10,11,12,15,16,17)
		AND coalesce(LpuUnit_FRMOUnitID,FRMOUnit.FRMOUnit_OID,FRMOSection.FRMOUnit_OID) IS NOT NULL
		AND (length(Token.PassportToken_tid::varchar(75))::bigint - length(REPLACE(Token.PassportToken_tid::varchar(75), '.', '')))/length('.')=10
	order by TimeTableHistory.TimeTableGrafHist_insDT
