isn't that possible with window functions and cte ? rank, and limit ?
pgsql-performance by date:
Соглашаюсь с условиями обработки персональных данных