2009-11-19 33 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 
相關問題