2012-10-19 65 views
0

我有一個工作的查詢,讓我的maxDate的最小和最大日期:獲得在同一個查詢

SELECT a.client_id AS client_id 
    , a.patientcount AS patientcount 
    , received_date AS maxRecDate 
FROM 
(
    SELECT DISTINCT CLIENT_ID 
    , PATIENT_ID 
    , count(*) over (partition by client_id, patient_id) AS patientcount 
    from f_accession_daily 
) AS a 
JOIN F_ACCESSION_DAILY AS f ON a.CLIENT_ID = f.CLIENT_ID 
    AND a.PATIENT_ID = f.PATIENT_ID 
GROUP BY f.RECEIVED_DATE, a.CLIENT_ID, a.patientcount 
HAVING f.RECEIVED_DATE = MAX(f.received_date) 

在相同的查詢,我也想回分鐘(f.received_date)。

有沒有辦法做到這一點?也許與子查詢?

+4

,請escpecially提供您表的結構,如果你的問題是所有關於'sql'。它幫助很多。 –

+0

你想把最短日期放在有或選擇? – PseudoToad

+0

@Gizmo我想要能夠返回最大和最小日期 –

回答

2

我可能失去了一些東西,但我不明白你爲什麼要通過f.RECEIVED_DATE

分組我想查詢可能是:

SELECT a.client_id AS client_id 
    , a.patientcount AS patientcount 
    , max(f.received_date) AS maxRecDate 
    , min(f.received_date) AS minRecDate 
FROM 
(
    SELECT DISTINCT CLIENT_ID 
    , PATIENT_ID 
    , count(*) over (partition by client_id, patient_id) AS patientcount 
    from f_accession_daily 
) AS a 
JOIN F_ACCESSION_DAILY AS f ON a.CLIENT_ID = f.CLIENT_ID 
    AND a.PATIENT_ID = f.PATIENT_ID 
GROUP BY a.CLIENT_ID, a.patientcount 

我沒有測試過這一點,但我認爲它應該工作。

1

在您的查詢中,添加OR條件以檢查MIN日期。解決以供將來參考問題

SELECT a.client_id AS client_id 
, a.patientcount AS patientcount 
, received_date AS maxRecDate 
FROM 
(
SELECT DISTINCT CLIENT_ID 
, PATIENT_ID 
, count(*) over (partition by client_id, patient_id) AS patientcount 
from f_accession_daily 
) AS a 
JOIN F_ACCESSION_DAILY AS f ON a.CLIENT_ID = f.CLIENT_ID 
AND a.PATIENT_ID = f.PATIENT_ID 
GROUP BY f.RECEIVED_DATE, a.CLIENT_ID, a.patientcount 
HAVING f.RECEIVED_DATE = MAX(f.received_date) 
OR f.RECEIVED_DATE = MIN(f.received_date) -- Newly added condition 
+0

非常感謝你,這幾乎是完美的。事情是我需要爲同一客戶和病人選擇最大和最小值 –