Median Order Value Per Customer Group
A food delivery platform wants to understand the spending behavior of its customers. They've categorized customers into groups based on their total spending. For each customer group, determine the median order value.
Tables:
customers:customer_id(int, PK),name(varchar(100))orders:order_id(int, PK),customer_id(int, FK),order_value(numeric(10,2)),order_date(date)
Return the customer group name (derived from total spending), and the median order value for that group. The groups are defined as follows:
- 'Low Spender': Total spending < 500
- 'Mid Spender': Total spending between 500 and 1500 (inclusive)
- 'High Spender': Total spending > 1500
Order the results by the derived group name alphabetically. Handle ties in order value by considering the lower order value as appearing first. Handle NULL order values by ignoring them. If a group has no orders, it should not appear in the result.
Tables
CREATE TABLE customers ( customer_id integer PRIMARY KEY, name varchar(100) ); CREATE TABLE orders ( order_id integer PRIMARY KEY, customer_id integer NOT NULL, order_value numeric(10,2), order_date date NOT NULL );
Example data
INSERT INTO customers (customer_id, name) VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie'), (4, 'David'), (5, 'Eve'); INSERT INTO orders (order_id, customer_id, order_value, order_date) VALUES (101, 1, 150.50, '2023-01-10'), (102, 1, 200.00, '2023-02-15'), (103, 2, 600.75, '2023-01-20'), (104, 2, 750.25, '2023-03-01'), (105, 2, 900.00, '2023-04-05'), (106, 3, 1600.00, '2023-02-01'), (107, 3, 1700.50, '2023-03-10'), (108, 4, 50.00, '2023-01-15'), (109, 4, 100.00, '2023-02-20'), (110, 5, 1200.00, '2023-03-05');
Your query is also checked on hidden datasets with different data.
Hints
Similar problems
- Median Customer Order Value by RegionHard
- Top Salaries per DepartmentHard
- Consecutive Delivery DelaysHard
- Sales Performance: Rank by Consecutive UpswingHard
- Cumulative Sales Over Time with LagHard
- Cricket Performance: Consecutive Matches Above AverageHard
More in: SQL and Databases problems
-- Calculate the median order value per customer spending group
SELECT
CASE
WHEN SUM(o.order_value) < 500 THEN 'Low Spender'
WHEN SUM(o.order_value) BETWEEN 500 AND 1500 THEN 'Mid Spender'
ELSE 'High Spender'
END AS customer_group,
-- Compute median order value here
FROM orders o
GROUP BY o.customer_id, CASE
WHEN SUM(o.order_value) < 500 THEN 'Low Spender'
WHEN SUM(o.order_value) BETWEEN 500 AND 1500 THEN 'Mid Spender'
ELSE 'High Spender'
END;
Your query runs on the example tables shown with the problem, then on hidden datasets when you submit.
Write standard SQL. MySQL habits work too: IFNULL, IF, YEAR(), DATE_FORMAT, GROUP_CONCAT, `backticks` and LIMIT 5, 10. It runs on PostgreSQL, so integer division keeps whole numbers (5 / 2 = 2): write 5.0 / 2 for 2.5.