HardSQL challenge #192CTECASE WHENSegmentationBusiness Analytics

Segment Customers by Recency, Frequency and Monetary Value (RFM)

Compute last order date, order count and spend per customer, then label each VIP, Regular, At-Risk or New.

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

Solve This SQL Challenge

The task

Segment customers by Recency (last order), Frequency (order count) and Monetary value. Label them as VIP, Regular, or At-Risk.

A correct answer returns 30 rows with 5 columns: name, last_order, frequency, monetary, segment.

Tables used in this challenge

users 150 rows

id INTEGER (PK) · first_name TEXT · last_name TEXT · email TEXT · phone TEXT · city TEXT · country TEXT · created_at TEXT · status TEXT · is_premium INTEGER

First 3 rows of the users table
idfirst_namelast_nameemailphonecitycountrycreated_atstatusis_premium
1JenniferTorresjennifer.torres57@icloud.com+1-263-376-2371HoustonCanada2024-04-13active0
2DonnaAdamsdonna.adams52@gmail.com+1-753-780-6670Fort WorthCanada2020-09-15inactive0
3KennethYoungkenneth.young94@proton.me+1-440-743-9503AustinUSA2023-09-05active0

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
1432638.110.253cancelled2024-04-24NULLLos AngelesUSA
2829470.195delivered2024-03-152023-04-09ChicagoUSA
3136683.240.082delivered2023-02-152023-07-10Los AngelesUSA

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
namelast_orderfrequencymonetarysegment
Paul Young2024-03-08313271.39Regular
Joseph King2024-08-16412979.86Regular
Michael Rodriguez2024-04-21412059.32Regular
Deborah Jones2024-08-17311528.59Regular
Maria Johnson2023-12-0329759.23Regular

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

What you practise

  • 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
  • Keeping every row of the left table with LEFT JOIN, matched or not
  • Naming an intermediate result with a WITH clause and reading from it
  • Turning conditions into values with CASE WHEN
  • Building and cutting text values
  • Sorting the result with ORDER BY
  • Returning only the first rows with LIMIT

Hint and approach

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

Show the hint

Calculate R/F/M per user, then use CASE WHEN to classify

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 rfm:
    1. Read from the users table.
    2. LEFT JOIN orders on orders.user_id = users.id, and only where orders.status is none of 'cancelled' or 'refunded'. Rows from the left side that have no match are kept, with NULL in the joined columns.
    3. Group the rows by users.id, so the result has one row for each value.
    4. For each group, compute MAX(orders.order_date), COUNT(orders.id) and SUM(orders.total).
    5. Build name by joining text values with the || operator.
    6. ROUND() trims the calculated figures to a fixed number of decimals.
  2. Read from the rfm CTE.
  3. Label each row with a CASE expression (segment): the conditions are tested in order and the first one that is true decides the value.
  4. Sort the result by monetary descending.
  5. Keep only the first 30 rows with LIMIT.

Model solution

Checking your session…

What to watch for

The status filter sits in the JOIN condition, not in WHERE. That keeps customers whose only orders were cancelled in the result with a frequency of 0; the same filter in WHERE would remove them. CASE returns the first branch that matches, so the order of the WHEN clauses decides the label.

  • 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.
  • LEFT JOIN. A WHERE condition on the right-hand table removes the unmatched rows and turns the LEFT JOIN back into an inner join. Conditions on that table go in the ON clause.
  • GROUP BY. Every selected column must either be in GROUP BY or sit inside an aggregate. SQLite accepts other columns and returns an arbitrary value for them; most databases raise an error.
Solve This SQL Challenge

Keep learning