WITH cte AS MATERIALIZED (
SELECT a.id, a.slug, r.earliest_review, r.review_total
FROM apps a
JOIN (
SELECT app_id, min(review_date) AS earliest_review, count(*)::int AS review_total
FROM reviews
GROUP BY 1
) r ON r.app_id = a.id
)
SELECT *
FROM (
SELECT generate_series(min(review_date)
, max(review_date)
, '1 day')::date
FROM reviews
) d(review_window_start)
LEFT JOIN LATERAL (
SELECT app_id, slug, review_total, earliest_review
FROM (
SELECT app_id, slug, review_total, earliest_review
, rank() OVER (ORDER BY review_total DESC, earliest_review DESC) AS rnk
FROM cte c
WHERE c.earliest_review >= d.review_window_start
) sub
WHERE rnk = 1
) a ON true;