换句话说,我需要为每个患者找到(最后一次就诊 - 6 个月)和最后一次就诊之间的就诊次数,不包括最后一次就诊。
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
这将按患者对最后一次就诊前六个月内的所有就诊进行分组。它会给你 COUNT(总数)减一(不包括最后一次访问)。
完整示例: http: //pastebin.com/vpCdASpB
对于第二部分(患者表),请参见此处: http: //pastebin.com/nKw0Wqvp
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;