I have a simple table that is used to record events against specific visits:
Describe Histories;
+------------------+
| Field |
+------------------+
| HistoryId |
| VisitId |
| Location |
| Event |
| EventTime |
+------------------+
Individuals are associated with Visits (VisitId). For each Visit, an individual may have multiple History records. Events can be Admission, Transfer or Discharge.
I am trying to write a Query to calculate the duration in each Location for each individual. Note, that they may visit a Location multiple times for each Visit. An individual enters a Location with an Admission or Transfer Event and leaves with a Discharge or Transfer.
If an individual enters Location 'A', their Admission or Transfer record will list Location 'A', however if they transfer out their transfer out (or discharge) will list another Location, say 'B'.
I therefore have to find the interval between the transfer into Location 'A' and the subsequent (in time) transfer to Location 'B'. Intra location transfers are not evaluated.
I understand that the solution will probably be based on an INNER JOIN, however I am at a loss to understand how to select for the transfer "out" record that corresponds to the most recent transfer "in".
I guess that this is reasonably complex - I hope I have been clear enough in my explanation.
Any guidance greatly appreciated.
Assuming a transfer or discharge is a unique event you could write like so
If you were interested in the last transfer or discharge you would write
However if a Visit can result in multiple visits as Andriy M mentions you have a Gaps And islands problem (specifically the islands)
In that case you want the following
DEMO
Using the following sample data
You get the following results
Notes:
How does this work for you?