Skip to the content

How soon they're back

Problem

Some customers are back the next day, and others take a week. The store wants the numbers for each customer: how many times they've come back, and how many days go by, on average, between one visit and the next.

A visit is a day with orders: two orders on the same day are one visit. Only orders dated up to today, January 15, 2026, count. The one dated the 20th has a mistyped date, and you can't count days from a wrong date: it's left out, even though that costs Luke one of his trips back.

Show the name, how many times they came back, and the average number of days, rounded to 1 decimal, in that order. Whoever comes back soonest goes first, and ties go by name. Anyone who has come in on only one day isn't on the list.

What it has to return

These rows, in this order

nametimes_backavg_days
Dylan11
Valerie12
Ann24.5
Luke17

This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.

You start with this

SQL

SELECT customer_id, placed,
  LAG(placed) OVER (
    PARTITION BY customer_id
    ORDER BY placed, id
  ) AS previous
FROM orders;
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →