Skip to content
Advertisement

How can I get SQL AdmitDate and DischargeDate with specific events?

Hi I have a table for homecare system and I have a series of entry logs for customer. I want to get a specific output. I want to break it down by record type ‘expired’, ‘Discharge’ and ‘Discharge-Returning’. if there is Admit and return events for a customer but there is no expired, discharge or discharge-returning event for that customer in between admit and return events then I want min admit date for that customer. If there is admit date or return date and no discharge event for that customer then I want to add 12/31/9999 showing that he is still in the location. please see how I want an output data below. I have added 4 customer data.

Here is my code.

Output:-

My New dataset is below. Now, I have converted all Return into “Admit” and Discharge, Discharge-Returning and Expired events into “Discharge” events. My new Dataset is as below. This would solve my entire dataset. Can someone resolve the query?

Desired Output:-

Advertisement

Answer

This answers the original version of the question.

This is tricky. The first piece is figuring out where the “stays” start. Obviously “admin” is one, but then you need special logic for the returns. The following query compares the date of the previous “admin” and “exit” status to determine if a “return” is the start of a new row.

After that, it is cumbersome aggregation:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement