在同一查询中获取最小和最大日期

时间:2012-10-19 03:13:52

标签: sql sql-server sql-server-2008 tsql

我有一个工作查询,它​​给了我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)

在同一个查询中,我还想返回min(f.received_date)。

有办法做到这一点吗?也许是子查询?

2 个答案:

答案 0 :(得分: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 :(得分: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