Skip to content
Advertisement

Is there a more efficient way of returning records that match the max value?

I have a table with fields of interest:

I want [Order] and [Shift] where [DateTime] is the largest value for each [Order]. So the above table would translate to:

Though I don’t need the DateTime field.

I have actually achieved this but the method feels overly convoluted (and takes a considerable time for the query to run) I have subqueries in both the from clause and one of the joins.

It feels like I should be able to do some kind of join in the where clause along the lines of “value=max(value) but I just can’t seem to figure it out as the subquery already has a join and also includes a case statement and I can’t seem to master the syntax.

This is the complete code I have:

What I’m most interested in is the [Shift] field.

Advertisement

Answer

One option is to use WITH TIES in concert with row_number()

Example

Returns

Full Disclosure: Using a sub-query with row_number() is a nudge more performant

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