In other words I need for each patient find number of visits between
(last visit-6 months) and last visit excluding last visit.
WITH CTE AS
(
SELECT PatientID, MAX(ActualDate) AS LastVisit
FROM Visits
GROUP BY PatientID
)
SELECT CTE.PatientID, COUNT(1)-1 AS RepeatVisits
FROM CTE INNER JOIN Visits ON CTE.PatientID = Visits.PatientID
WHERE ActualDate BETWEEN DATEADD(month, -6, LastVisit) AND LastVisit
GROUP BY CTE.PatientId
这将按病人分类,在上一次访问之前六个月内进行所有访问。 它将给你(总数)减去(不包括最后一次访问)。
完整的实例:
第二阶段见:。
WITH CTE AS
(
SELECT Patients.PatientID, Patients.Name, MAX(ActualDate) AS LastVisit
FROM Patients LEFT JOIN Visits ON #patient.PatientID = Visits.PatientID
GROUP BY Patients.PatientID, Patients.Name
)
SELECT CTE.PatientID, CTE.Name, COUNT(1)-1 AS RepeatVisits
FROM CTE LEFT JOIN Visits ON CTE.PatientID = Visits.PatientID
AND Visits.ActualDate BETWEEN DATEADD(month, -6, LastVisit) AND LastVisit
GROUP BY CTE.PatientId, CTE.Name
ORDER BY PatientID;