I'm trying to write a query that does the following:
- Take the Start_Date and End_Date from the Visit table
- For each date inclusive in the date range, search the encounter table to see if a patient was seen by certain providers on that date
- Generate a table that shows each date and who saw the patient on that date.
- Notes:
- The patient may not have been seen on that date which should result to NULL or something similar
- More than one provider may have seen the patient on a date which should result in more than one line for that date.
Simplified Example:
Start_Date: 01-JAN-15
End_Date: 04-JAN-15
Desired Output:
╔══════╦══════════╦═══════╦═══════╗
║ ID ║ DATE ║ NAME ║ TYPE ║
╠══════╬══════════╬═══════╬═══════╣
║ 2222 ║ 1-Jan-15 ║ Smith ║ Note ║
║ 2222 ║ 2-Jan-15 ║ Jones ║ Note ║
║ 2222 ║ 2-Jan-15 ║ Smith ║ Order ║
║ 2222 ║ 3-Jan-15 ║ NULL ║ ║
║ 2222 ║ 4-Jan-15 ║ Jones ║ Note ║
╚══════╩══════════╩═══════╩═══════╝
Here is what I've got so far. This generates a list of when these certain providers saw the patients but it does not result NULL for those dates when they were not seen.
SELECT V.VISIT_ID, ET.ENCOUNTER_TRANSACTION_DATE, P.NAME_LAST, ETT.ENC_TRANS_TYPE_NAME
FROM VISIT V
RIGHT OUTER JOIN ENCOUNTER_TRANSACTION ET ON V.VISIT_ID = ET.VISIT_ID AND V.INSTITUTION_ID = ET.INSTITUTION_ID
INNER JOIN ENCOUNTER_TRANSACTION_TYPE ETT ON ET.ENCOUNTER_TYPE_ID = ETT.ENCOUNTER_TRANSACTION_TYPE_ID
INNER JOIN LOCAL_PROVIDER LP ON ET.ORDERING_PROVIDER_ID = LP.LOCAL_PROVIDER_ID
INNER JOIN PERSON_IDENTIFIER I ON I.IDENTIFIER = LP.PROVIDER_NUMBER AND I.IDENTIFIER_SYS_ID = LP.PROVIDER_NUMBER_SYS_ID
INNER JOIN PERSON P ON P.PERSON_ID = I.PERSON_ID
WHERE
V.INSTITUTION_ID = 1 AND
V.END_DATE IS NOT NULL AND
V.VOIDED_YN = 'N' AND
V.CARE_SETTING_CODE = 'I' AND
V.PATIENT_TEAM_ID IN (16, 17, 18) AND
V.START_DATE >= (TRUNC(ADD_MONTHS(CURRENT_DATE, -1),'mon')) AND
V.START_DATE <= (LAST_DAY(ADD_MONTHS(CURRENT_DATE, -1))) AND
I.IDENTIFIER IN (
'1234', --Smith
'4321', --Jones
)
ORDER BY V.VISIT_ID ASC, ET.ENCOUNTER_TRANSACTION_DATE ASC;
Current Output (Missing the NULL line for 03-JAN-15):
╔══════╦══════════╦═══════╦═══════╗
║ ID ║ DATE ║ NAME ║ TYPE ║
╠══════╬══════════╬═══════╬═══════╣
║ 2222 ║ 1-Jan-15 ║ Smith ║ Note ║
║ 2222 ║ 2-Jan-15 ║ Jones ║ Note ║
║ 2222 ║ 2-Jan-15 ║ Smith ║ Order ║
║ 2222 ║ 4-Jan-15 ║ Jones ║ Note ║
╚══════╩══════════╩═══════╩═══════╝
select start_date + level from dual connect by level <= 10
) and partition outer join your main query to it, in order to generate the rows for each day. – Boneist