Most analytics questions are variations on a small number of query shapes. Once you recognise the shape, the query almost writes itself. Here are eight that cover a large share of day-to-day analyst work, each runnable on the LearnWithSQL sandbox databases.
1. Top N per group
"The two best-paid people in each department."
WITH ranked AS (
SELECT department_id, first_name, salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC, id) AS rn
FROM employees
)
SELECT department_id, first_name, salary
FROM ranked
WHERE rn <= 2
ORDER BY department_id, rn;
Use ROW_NUMBER for exactly N rows, RANK if tied values should all be included.
2. Period-over-period change
"How did orders change from last month?"
WITH monthly AS (
SELECT DATE_TRUNC('month', order_date) AS month, COUNT(*) AS orders
FROM orders
GROUP BY 1
)
SELECT month, orders,
LAG(orders) OVER (ORDER BY month) AS prev_month,
ROUND(100.0 * (orders - LAG(orders) OVER (ORDER BY month))
/ NULLIF(LAG(orders) OVER (ORDER BY month), 0), 1) AS pct_change
FROM monthly
ORDER BY month;
NULLIF(…, 0) turns a zero denominator into NULL so the query does not fail on a month with no orders.
3. Running total
"Cumulative revenue over time."
WITH daily AS (
SELECT o.order_date, SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.order_date
)
SELECT order_date, revenue,
SUM(revenue) OVER (ORDER BY order_date) AS cumulative_revenue
FROM daily
ORDER BY order_date;
Aggregating to one row per day first means each date appears once, so the running sum steps cleanly.
4. Percent of total
"What share of payroll does each department take?"
SELECT department_id,
SUM(salary) AS payroll,
ROUND(100.0 * SUM(salary) / SUM(SUM(salary)) OVER (), 1) AS pct_of_total
FROM employees
GROUP BY department_id
ORDER BY payroll DESC;
SUM(SUM(salary)) OVER () is a window over the grouped result: the inner SUM is per department, the outer one adds them all up.
5. Cohorts
"Group customers by the month of their first order."
WITH first_order AS (
SELECT customer_id, MIN(order_date) AS first_date
FROM orders
GROUP BY customer_id
)
SELECT DATE_TRUNC('month', first_date) AS cohort_month,
COUNT(*) AS new_customers
FROM first_order
GROUP BY 1
ORDER BY 1;
From here you can join back to orders to see how many customers from each cohort ordered again in later months, which is the basis of a retention table.
6. Funnel and status breakdown
"How many appointments end in each state, per doctor?"
SELECT doctor_id,
COUNT(*) AS booked,
COUNT(*) FILTER (WHERE status = 'completed') AS completed,
COUNT(*) FILTER (WHERE status = 'no-show') AS no_shows,
ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'completed') / COUNT(*), 1) AS completion_rate
FROM appointments
GROUP BY doctor_id
ORDER BY booked DESC;
One pass over the table produces every stage side by side, which is the shape dashboards need.
7. Deduplication: latest row per entity
"Each customer's most recent order."
SELECT DISTINCT ON (customer_id) customer_id, id AS order_id, order_date
FROM orders
ORDER BY customer_id, order_date DESC, id DESC;
DISTINCT ON is PostgreSQL-specific; elsewhere use ROW_NUMBER() … WHERE rn = 1 from pattern 1.
8. Filling gaps in a time series
"Orders per day, including days with zero orders."
WITH days AS (
SELECT generate_series(
(SELECT MIN(order_date) FROM orders),
(SELECT MAX(order_date) FROM orders),
INTERVAL '1 day')::date AS day
)
SELECT d.day, COUNT(o.id) AS orders
FROM days d
LEFT JOIN orders o ON o.order_date::date = d.day
GROUP BY d.day
ORDER BY d.day;
Charts built on data with missing days are misleading because the line jumps straight across the gap. Generating a calendar and left-joining to it puts the zeros back.
Putting them together
Real questions combine these shapes. "Which product categories grew fastest last quarter, as a share of total revenue?" is pattern 4 inside pattern 2. Practise each shape on its own in the SQL playground until you can write it without looking, and the combinations stop feeling hard.