2009-11-19 31 views
0

这个查询:我需要检索这些结果的最后一个? (T-SQL)

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

你可以尝试通过采取actDate出了组,并使用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 
0
SELECT refPatient_id,MAX(actDate) 
FROM PatientClinicHistory 
WHERE refClinic_id = 24 
GROUP BY refPatient_id 

将计算最大actDate针对每个患者。这是你想要的吗?

+0

不要忘记AND active = 0 – Broam 2009-11-19 19:52:39

+0

是的,这是我想要的。 – uzay95 2009-11-19 19:54:33

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 
相关问题