--truncate table TeleHealthPatientLatestMeasurements 

--insert into TeleHealthPatientLatestMeasurements (PatientId, MeasurementType, FieldCode, TeleHealthDeviceMeasurementId, Severity,[rank])
--SELECT ResidentId,MeasurementType,FieldCode,id,abs(case when Severity is null then 0 else Severity end),rank
--    FROM (
--        SELECT panelid,e.ResidentId,e.LocalReadingTime,m.*, row_number() 
--          over (Partition BY panelid,fieldCode ORDER BY e.localreadingtime DESC ) AS Rank
--        FROM TeleHealthEvents e
--			join TeleHealthDeviceMeasurements m on e.id=m.TeleHealthEventId and e.ResidentId>0 and m.Invalidated is null
--			join CmsUserTbl u on u.cmsuserid=e.ResidentId
--		where	(MeasurementType!='Weight' and severity is not null)
--			or 
--				(MeasurementType='Weight')
--        ) rs 
--WHERE Rank <= 2
--	--and (MeasurementType='Weight' or severity is not null)
--order by ResidentId desc,FieldCode,LocalReadingTime desc
