Re: Finding "most recent" using daterange

From: Greg Sabino Mullane <htamfids(at)gmail(dot)com>
To: Rob Foehl <rwf(at)loonybin(dot)net>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Finding "most recent" using daterange
Date: 2024-05-22 14:14:25
Message-ID: CAKAnmmLBxrQ0n4+BPb_xBQKrDRoiq4eSKdQYDbnmo7KTQVFuRg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

This is a good candidate for a window function. Also note that nulls
already get sorted correctly by the DESC so no need to get 'infinity'
involved, although you could write 'DESC NULLS FIRST' to be explicit about
it.

with x as (select *, row_number() over (partition by id order by
upper(dates) desc, lower(dates) desc) from example)
select id,value,dates from x where row_number = 1;

id | value | dates
----+-------+-------------------------
1 | b | [2010-01-01,)
2 | d | [2010-01-01,2021-01-01)
3 | g | [2013-01-01,)
4 | j | [2010-01-01,2015-01-01)
(4 rows)

Cheers,
Greg

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Ron Johnson 2024-05-22 14:27:41 search_path and SET ROLE
Previous Message XChy 2024-05-22 13:41:08 Re: Missed compiler optimization issue in function select_rtable_names_for_explain