I’ve got a table in SQL Server that represents doctor/patient encounters. One of the columns is a datetime field that represents when the encounter began. There is another field that represents the SCHEDULED time for the encounter.
I’m trying to write a query to isolate one encounter (for a given day) that meets the following criteria:
- If any encounters have begun, the LAST encounter to begin, – OR –
- If NO encounters have begun, the FIRST scheduled encounter
So, I kind of want the following:
SELECT
TOP 1 *
FROM
TABLE
ORDER BY
CASE WHEN STARTED IS NULL THEN 0 ELSE 1 END DESC,
IF STARTED IS NULL
SCHEDULED ASC
ELSE
STARTED DESC
I realize that I can’t do that exactly, but I was wondering if I’m missing some other way to do this.
Other information:
- All encounters to be compared will occur on the same calendar day.
- This is part of a larger query where I’m partitioning by the room in which the encounter occurred/is scheduled.
- As long as I can accurately identify that one encounter, I don’t care about the rest of the encounters in that room.
I’m not sure whether it was particularly clear in my question, but based on the specific criteria of my scenario, the answer was a lot easier than I thought.
Basically, it boils down to the fact that I want to split the rows into 2 groups:
Also important is the fact that there is ALWAYS a valid value in the SCHEDULED field.
I want to sort group #1 by their STARTED values in descending order and group #2 by their SCHEDULED values in ascending order.
Then, I want the first entry from group #1, or – if group #1 is empty – the first entry from group #2. No other entries are important for this problem.
Because group #1 is desired to be sorted in descending order, the following solution is what I’ve used:
In my testing, this gives me the row with the latest STARTED value, or the row with the earliest SCHEDULED value, if all rows have a null STARTED value.