Skip to content
Advertisement

SQL Select column based on MIN value of another column after left join

I have a table with the column as below, lets call the table Incident:

IncidentId, IncidentType, StartDate, EndDate

I need to find the EndDate of the previous Incident based on the nearest previous EndDate and EventType for each Incident. So for a starting point I wrote a query as below:

But I don’t know how to go further. I had a go at the nested query with GROUP BY and MIN, the issue with that is that I need the EndDate of i2 but if I do GROUP BY on Id and EndDate I will end up with what I started with.

What I need at the end of day is to be to do at the end of day is something along the lines of:

Given the sample table below:

I am hoping to get the following results:

Explanation:
Whenever we EventType is not 3 we want to use the EndDate of nearest previous Incident of EventType 1 if such an EventType exists previously

EDIT: I add some sample data and extend query a bit more to add some more depth to the query.

Advertisement

Answer

The most straight-forward method is to use lateral join (CROSS/OUTER APPLY) in SQL Server.

LAG is tempting, but you need not just the previous row, you need to skip some rows in some cases, so I don’t see how LAG can be used here. If you didn’t have that requirement to look only at rows with IncidentType = 1, then you could use LAG.

Sample data

Query

Result

You’d better create an index on (IncidentType, EndDate).

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