Skip to content
Advertisement

SELECT from a table partition by order and status

So I have the following Searches table:

The status is a combination of ClosedOn and ClosedByUserID:

  • Pending: If ClosedOn and ClosedByUserId are null
  • Outdated: If ClosedOn is not null and ClosedByUserID is null
  • Closed: If ClosedOn is not null and ClosedBYUserID is not null

I am trying to select all records and trying to filter the duplicate outdated records and just show the latest one. I would still want to see multiple closed searches after each other, and there can only be one pending.

From the above example the result expected would be:

I have tried using Partitions to select the rows where Status is Closed or Status is Pending or (Status is Outdated and RN = 1):

However the result is appearing as follows and RN is not being reset to 1 after the closed record

Is Partition the correct way to approach this? And if so what am i missing?

** updated to have also the scenario where two searches are closed after each other, which i still would want to display

Advertisement

Answer

I am trying to select all records and trying to filter the duplicate outdated records and just show the latest one.

This means that the next record does not have a status of 'OUTDATED' when the current record has that status.

Use lead():

Note: I’m not sure if “latest” refers to the id or CreatedOn. The above uses id — the two are equivalent in your sample data.

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