Skip to content
Advertisement

Select first two distinct occurrences and return rowid

I have a table like this:

I want to select the first N distinct room_ids and a row_id of the last one. For example I want to select first two distinct rooms_ids and return a row_id of the last one. The result should be:

The row_id should be identified with this record:

I have already written my SQL statement but it does not work:

‘N’ is a value of how many distinct room_ids I want to select. I also don’t know how to return the row_id of the last record.

Advertisement

Answer

You can try in this manner :

Demo

The important point of interest is considering order by time desc within the row_number() analytic function and grabbing the rn = 1 for the outer query.

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