🌐 Machine-translated from Russian. Show original
You don't need to know all SQL analytics — you need to confidently solve typical business tasks. Below are 10 queries that cover most daily questions. Examples for PostgreSQL on tables orders(id, customer_id, amount, status, created_at) and customers(id, city, created_at).
In this part:
1. Revenue by month
SELECT date_trunc('month', created_at) AS month,
sum(amount) AS revenue, count(*) AS orders
FROM orders WHERE status = 'paid'
GROUP BY 1 ORDER BY 1;
2. Average check and median
SELECT avg(amount) AS avg_check,
percentile_cont(0.5) WITHIN GROUP (ORDER BY amount) AS median_check
FROM orders WHERE status = 'paid';
The median is fairer than average when there are rare large orders.
3. Top 10 Clients
SELECT customer_id, sum(amount) AS total, count(*) AS orders
FROM orders WHERE status = 'paid'
GROUP BY customer_id ORDER BY total DESC LIMIT 10;
