Business Analytics · Problem 88 of 118

Customer Activity Segments

HardBusiness AnalyticsShop data

As of 2026-09-30, look at each customer's most recent non-cancelled order (customers with none are ignored). Put the customer into a segment by the number of days since that order:

  • 'active': 90 days or fewer
  • 'at risk': 91 to 180 days
  • 'lapsed': more than 180 days

Return segment and customers (how many customers), sorted by customers from high to low, then segment.

Hint 1

First one row per customer with MAX(order_date), then a CASE on JULIANDAY('2026-09-30') - JULIANDAY(last_date), then group by the segment.

Reference solution

WITH last_orders AS (
  SELECT customer_id, MAX(order_date) AS last_date
  FROM orders
  WHERE status <> 'cancelled'
  GROUP BY customer_id
)
SELECT CASE
         WHEN JULIANDAY('2026-09-30') - JULIANDAY(last_date) <= 90 THEN 'active'
         WHEN JULIANDAY('2026-09-30') - JULIANDAY(last_date) <= 180 THEN 'at risk'
         ELSE 'lapsed'
       END AS segment,
       COUNT(*) AS customers
FROM last_orders
GROUP BY segment
ORDER BY customers DESC, segment;

Recency is the "R" of the classic RFM analysis (recency, frequency, monetary value). Notice the fixed reference date: reports that use "today" give different answers every day and cannot be checked, so analysts pass the as-of date explicitly. GROUP BY segment uses the alias of the CASE expression, which SQLite allows (other databases may need the expression repeated). A customer whose only order was cancelled has no row at all in last_orders, because the filter removes it before grouping.