I have these tables
Records:
+----+-------------+--------------+-------------------------+---------+
| Id | IdHealtcare | ValueMonitor | DateMonitor | Checked |
+----+-------------+--------------+-------------------------+---------+
| 1 | 1 | 80 | 2020-05-14 19:40:11.873 | NULL |
| 2 | 2 | 66 | 2020-05-14 20:56:33.360 | NULL |
| 3 | 1 | 100 | 2020-05-14 20:32:24.397 | NULL |
| 4 | 3 | 87 | 2020-05-14 20:57:12.390 | NULL |
+----+-------------+--------------+-------------------------+---------+
Healthcare:
+----+-----------+----------+--------+------------+
| Id | IdPatient | IdDoctor | IdType | RangeValue |
+----+-----------+----------+--------+------------+
| 1 | 1 | 1 | 1 | 0-180 |
| 2 | 1 | 1 | 2 | 50-200 |
| 3 | 2 | 2 | 1 | 90-180 |
+----+-----------+----------+--------+------------+
I want to select for each type of patient's healtcare the Id of the patient and the most recent date with it value.
I have already tried with these query:
select p.CodiceFiscale, p.Surname, p.Name, t.Name, Max(r.DateMonitor),
r.ValueMonitor
from dbo.Patients as p
inner join dbo.HealtcareMonitoring as m on m.IdPatient = p.Id
inner join dbo.Records as r on r.IdHealtcare = m.Id
inner join dbo.MonitoringTypes as t on t.Id = m.IdType
where m.IdDoctor = 1
group by t.Name, p.CodiceFiscale, p.Surname, p.Name
SELECT m.IdPatient, m.IdType, MAX(r.DateMonitor), r.ValueMonitor AS LastDate
FROM dbo.Records as r
inner join dbo.HealtcareMonitoring as m on m.Id = r.IdHealtcare
where m.IdDoctor = 1
GROUP BY m.IdPatient, m.IdType
But I can't select the value because it is not contained in either an aggregate function or the "group by" clause.
How can I fix? Are there a better ways to solve the problem?