Public EcoRouter Knowledge · AI-generated content ·
Write a SQL query that finds the top 5 customers by total order value in the last 12 months, and explain how it works.
The question
Write a SQL query that finds the top 5 customers by total order value in the last 12 months, and explain how it works. Assume tables customers(id, name) and orders(id, customer_id, total, created_at).
This answers a time-sensitive question. It reflects information found by a live search as of and may no longer be current.
Here is the SQL query (written for standard SQL/PostgreSQL/MySQL):
SELECT
c.id AS customer_id,
c.name AS customer_name,
SUM(o.total) AS total_spent
FROM customers c
JOIN orders o
ON c.id = o.customer_id
WHERE o.created_at >= CURRENT_DATE - INTERVAL '12 month'
GROUP BY
c.id,
c.name
ORDER BY
total_spent DESC
LIMIT 5;How it works step-by-step:
-
JOIN orders o ON c.id = o.customer_id
Combines thecustomersandorderstables by matching each customer to their respective orders. AnINNER JOINis used so that customers with no orders during the timeframe are excluded. -
WHERE o.created_at >= CURRENT_DATE - INTERVAL '12 month'
Filters out any orders placed older than 12 months from the current date. (Note: depending on the SQL dialect, date syntax can vary slightly—e.g.,NOW() - INTERVAL 12 MONTHin MySQL,DATEADD(month, -12, GETDATE())in SQL Server). -
GROUP BY c.id, c.name
Groups the records by customer so we can perform aggregation per individual. Grouping by bothidandnameensures uniqueness even if two customers share the same name. -
SUM(o.total) AS total_spent
Calculates the sum of all order totals for each customer within that 12-month window. -
ORDER BY total_spent DESC
Sorts the grouped results from the highest spenders to the lowest. -
LIMIT 5
Restricts the final output to only the top 5 highest-spending customers. (In SQL Server or Oracle, you would useTOP 5orFETCH FIRST 5 ROWS ONLYinstead).
Answering this used an estimated 75% less than EcoRouter’s configured frontier baseline
- Routed to
- Balanced
- Tokens
- 1,109 in / 548 out
- Cost
- $0.0029
- Baseline
- $0.01
Figures recorded by EcoRouter when this answer was generated, and fixed at that moment. Cost comparisons are against a configured reference model, not a measurement of electricity, carbon or water.
Ask about this
Ask EcoRouter a follow-up using this Knowledge as context. Nothing becomes public unless you choose to publish it.
Ask a follow-upComments
No comments yet.