← Knowledge

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).

Balanced

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):

sql
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:

  1. JOIN orders o ON c.id = o.customer_id
    Combines the customers and orders tables by matching each customer to their respective orders. An INNER JOIN is used so that customers with no orders during the timeframe are excluded.

  2. 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 MONTH in MySQL, DATEADD(month, -12, GETDATE()) in SQL Server).

  3. GROUP BY c.id, c.name
    Groups the records by customer so we can perform aggregation per individual. Grouping by both id and name ensures uniqueness even if two customers share the same name.

  4. SUM(o.total) AS total_spent
    Calculates the sum of all order totals for each customer within that 12-month window.

  5. ORDER BY total_spent DESC
    Sorts the grouped results from the highest spenders to the lowest.

  6. LIMIT 5
    Restricts the final output to only the top 5 highest-spending customers. (In SQL Server or Oracle, you would use TOP 5 or FETCH FIRST 5 ROWS ONLY instead).

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-up
0 views

Comments

No comments yet.