Premium problem72. Time to Second Purchase

Medium Locked

orders(order_id, user_id, ordered_at)

For users with at least two purchases, return the whole hours between their first and second purchase, truncated rather than rounded. Where two orders share a timestamp, the lower order_id comes first.

Return user_id and hours_to_second_purchase, ordered by user_id. Users with one order are left out.

MIN(ordered_at) gives the first easily enough; the second is the one that needs ranking.

Tables

orders

order_id  user_id  ordered_at
--------  -------  -------------------
1         10       2026-01-01 00:00:00
2         10       2026-01-03 06:00:00
3         10       2026-02-01 00:00:00
4         11       2026-01-01 09:00:00
5         11       2026-01-01 09:00:00
6         12       2026-01-01 00:00:00
7         12       2026-01-01 23:59:00
8         13       2026-01-05 00:00:00

Expected result

user_id  hours_to_second_purchase
-------  ------------------------
10       54
11       0
12       23

Premium problem

This one's part of Premium. Unlock the full MySQL track plus every other premium problem on the site.

Write one SELECT query