Alex Gordon
Alex Gordon

Reputation: 60691

getting the minimum and maximum date in the same query

I have a working query that gives me the 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)

In the same query I would also like to return min(f.received_date).

Is there a way to do this? perhaps with the subquery?

Upvotes: 0

Views: 3804

Answers (2)

tempidope
tempidope

Reputation: 863

In your query, add an OR condition to check for MIN date as well. Solves the problem

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

Upvotes: 1

Cristian Lupascu
Cristian Lupascu

Reputation: 40506

I might be missing something, but I don't see why you are grouping by f.RECEIVED_DATE

I think the query could be:

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

I haven't tested this, but I think it should work.

Upvotes: 2

Related Questions