Skip to content
Advertisement

SQL – Convert ROW_NUMBER function with multiple order by

I am trying to convert this query to a subquery without the ROW_NUMBER function:

Basically this is selecting the most recent [Investor.Fund.History] within a time period and depending on the status.

So far I have this:

My query gives the incorrect results and it does this because when i use the MAX function on multiple columns, it does not select the max based on the order of both columns like the ROW_NUMBER does, instead it selects the MAX no matter both columns order positions.

For example, if I have a subset of data which looks like this:

The ROW_NUMBER function will return the following:

Whereas my function returns this:

Which as you can see, is not actually a row in the table.

I would like my function to correctly return the row in the table based on the MAX AsOfDATE AND AddedOn

Can anyone help?

Advertisement

Answer

If you have a unique id that identifies each row, then you can do:

The ? is for the column that uniquely identifies each row.

This is also possible to do using APPLY:

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