此查询:
SELECT refPatient_id,actDate,refReason_id,refClinic_id,active
FROM PatientClinicHistory
WHERE refClinic_id = 24
GROUP BY refPatient_id,actDate,refReason_id,refClinic_id,active
ORDER BY refPatient_id,actDate
返回此结果:
refPatient_id actDate refReason_id refClinic_id active
============= ==================== ============ ============ ======
15704 2009-02-09 12:48:00 19 24 0
15704 2009-02-10 10:25:00 23 24 1
15704 2009-02-10 10:26:00 19 24 0
15704 2009-02-12 10:16:00 23 24 1
15704 2009-02-13 15:41:00 19 24 0
15704 2009-04-14 17:48:00 19 24 0
15704 2009-06-24 16:06:00 19 24 0
15731 2009-05-20 12:19:00 19 24 0
16108 2009-07-20 11:08:00 19 24 0
16139 2009-03-02 13:55:00 19 24 0
16569 2009-07-13 15:57:00 20 24 0
17022 2009-06-02 16:02:00 19 24 0
17022 2009-08-19 15:08:00 19 24 0
17022 2009-09-01 15:47:00 21 24 0
17049 2009-02-02 16:49:00 19 24 0
17049 2009-02-04 15:16:00 19 24 0
17063 2009-07-22 11:35:00 21 24 0
17063 2009-07-28 10:14:00 22 24 1
17502 2008-12-15 17:25:00 19 24 0
我需要让每个病人的最后一个被动行(主动= 0)(所以我需要为每个病人获得最大的actDate)。
在获得所有这些结果后,我应该编写一个新查询来过滤它吗?
编辑: 感谢您的回复,实际上我需要为每位患者采取最后的行动。 e.g:
17022 2009-06-02 16:02:00 19 24 0
17022 2009-08-19 15:08:00 19 24 0
17022 2009-09-01 15:47:00 21 24 0
我需要过滤最后一行(每个病人的最大actDate)。
17022 2009-09-01 15:47:00 21 24 0
答案 0 :(得分:0)
SELECT refPatient_id,MAX(actDate)
FROM PatientClinicHistory
WHERE refClinic_id = 24
GROUP BY refPatient_id
将计算每位患者的最大actDate。这是你想要的吗?
答案 1 :(得分:0)
您可以尝试将actDate从群组中删除并使用max function max(actDate)
像
SELECT refPatient_id,Max(actDate),refReason_id,refClinic_id,active FROM PatientClinicHistory WHERE refClinic_id = 24 AND active = 0 GROUP BY refPatient_id,refReason_id,refClinic_id,active ORDER BY refPatient_id
答案 2 :(得分:0)
您可以使用CTE
;WITH PatientClinicHistoryNew AS
(
SELECT refPatient_id,actDate,refReason_id,refClinic_id,active
FROM PatientClinicHistory
WHERE refClinic_id = 24
GROUP BY refPatient_id,actDate,refReason_id,refClinic_id,active
ORDER BY refPatient_id,actDate
)
SELECT refPatient_id, Max (actDate)
FROM PatientClinicHistoryNew
WHERE 1=1
AND active = 0
GROUP BY refPatient_id