Skip to content
Advertisement

How to obtain row for minimum date for a value that is equal to the value in maximum date, per group?

I am trying to obtain row for a query.. where row value1, value2 in minimum end_date is equal to the max end_date, per group of id’s.

My current query only obtains the row value1, value2 from the max end_date in the query result:

This result obtains the most recent record, but I’m looking to obtain the row where value1 & value2 in min(end_date = max(end_date), grouped by id.

Here is an example query detailing what I want to obtain:

id end_date value1 value2
AAPL 02/12/22 2 1
AAPL 02/13/22 2 1
AAPL 02/14/22 3 2
AAPL 02/15/22 3 2
MSFT 03/01/22 2 5
MSFT 03/02/22 4 5
MSFT 03/03/22 4 5
MSFT 03/04/22 4 5

From this previous query, the query that I need to obtain is the following:

id end_date value1 value2
AAPL 02/14/22 3 2
MSFT 03/02/22 4 5

So once again, I need the row where value1, value2 in min(end_date) = max(end_date), grouped by id.

Advertisement

Answer

You can do it with row_number()

db<>fiddle

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