EasyGROUP BY & Aggregation

Sum total sales per customer

The query

SQL
SELECT
  c.name AS customer,
  COUNT(o.order_id) AS total_orders,
  SUM(o.total) AS total_spent,
  ROUND(AVG(o.total), 2) AS avg_order_value
FROM customers c
LEFT JOIN orders o ON c.cust_id = o.cust_id
GROUP BY c.cust_id, c.name
ORDER BY total_spent DESC NULLS LAST;
Tested against PostgreSQL 16

Note

NULLS LAST in ORDER BY puts NULL values at the end, useful when some customers have no orders.

Tables referenced