HardSQL challenge #310SELF JOINDATEAGGREGATION

Count Each Customer's Orders in a Rolling 30-Day Window

Return each customer with the largest number of orders they placed within any 30-day period, busiest first.

The challenge runs on the SQLabHub practice database (SQLite) and uses the orders table. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

Why this question comes up

The fraud team watches for customers who suddenly order much more often than usual. A first measure is the largest number of orders each customer placed within any 30-day period.

The task

For each customer, find the largest number of orders they placed within any 30-day period. List customers with the busiest period first.

A correct answer returns 114 rows with 2 columns: user_id, max_orders_30d.

Tables used in this challenge

orders 200 rows

id INTEGER (PK) · user_id INTEGER · total REAL · discount REAL · item_count INTEGER · status TEXT · order_date TEXT · shipped_date TEXT · shipping_city TEXT · shipping_country TEXT

First 3 rows of the orders table
iduser_idtotaldiscountitem_countstatusorder_dateshipped_dateshipping_cityshipping_country
143321.680.259cancelled2024-04-24NULLDelhiIndia
2810.520.191delivered2024-03-152024-03-20ColumbusUSA
3136181.190.085delivered2023-02-152023-02-18ChicagoUSA

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
user_idmax_orders_30d
442
472
1242
11
21

First 5 of 114 rows. This is the output of the model solution on the practice database.

What you practise

  • Filtering a range of values with BETWEEN
  • Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
  • Grouping rows with GROUP BY to get one result row per group
  • Grouping by more than one column to get a row per combination
  • Combining rows from two tables on a matching key with an inner join
  • Joining a table to itself under two aliases
  • Naming an intermediate result with a WITH clause and reading from it
  • Working with dates in SQLite: strftime, julianday and DATE
  • Sorting the result with ORDER BY

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

Self join each order to the same customer's orders in the 29 days after it, count per starting order, then take the MAX per customer

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Define a common table expression named windows:
    1. Read from the orders table, under the alias o1.
    2. Join orders again, under the alias o2, on o2.user_id = o1.user_id, and only where o2.order_date is between o1.order_date and 29 days after o1.order_date, both ends included.
    3. Group the rows by o1.user_id and o1.id, so the result has one row for each combination.
    4. For each group, compute COUNT(*).
  2. Read from the windows CTE.
  3. Group the rows by user_id, so the result has one row for each value.
  4. For each group, compute MAX(orders_in_window).
  5. Sort the result by max_orders_30d descending, then user_id.
Show the model solution
WITH windows AS (
  SELECT o1.user_id, o1.id AS first_order, COUNT(*) AS orders_in_window
  FROM orders o1
  JOIN orders o2
    ON o2.user_id = o1.user_id
   AND o2.order_date BETWEEN o1.order_date AND DATE(o1.order_date, '+29 day')
  GROUP BY o1.user_id, o1.id
)
SELECT user_id, MAX(orders_in_window) AS max_orders_30d
FROM windows
GROUP BY user_id
ORDER BY max_orders_30d DESC, user_id;

This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.

What to watch for

SQLite window frames cannot span a number of days, so the window is built with a self join on a date range. Each order starts a window covering that day and the next 29, the count includes the order itself, and MAX() keeps each customer's busiest window. Grouping by the order id rather than the date keeps two orders on the same day from merging.

  • CTE (WITH). A CTE exists only for the single statement it is attached to. It is not a temporary table and cannot be reused by the next query.
  • Self join. Without a condition such as a.id < b.id, a self join pairs every row with itself and lists each pair twice.
  • INNER JOIN. An inner join drops rows that have no partner on the other side, and it repeats a row once for every match, which inflates SUM and COUNT.
Solve This SQL Challenge

Same technique, other tables

More practice on this pattern with different columns:

Keep learning