Developer Guides, Cheat Sheets & Tools

SQL course - Part 7: ANALYTICS

Part index Prerequisites Previous Next Full course

📈 PART 7 — ANALYTICS


33. Window functions

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡 Intermediate 40 min Add group totals and ranks without losing rows · Compare each row with the previous one · Control exactly which rows a calculation sees

[!NOTE] 📌 In plain words: A window function performs a calculation across a set of related rows, without collapsing them into one row. GROUP BY gives you 6 rows from 18. A window function gives you 18 rows, each carrying its group’s answer alongside it.

🌍 Analogy: In a classroom, GROUP BY gives the teacher one sheet with the class average. A window function gives each student their own report card showing their mark, the class average, and their rank — every student keeps their own row.

33.1 🪟 The anatomy of a window function

The word window means the set of rows the function is allowed to look at while it works on each row.

FUNCTION_NAME(...) OVER (
    [PARTITION BY column]     <- split rows into windows (like GROUP BY, but keeps rows)
    [ORDER BY column]         <- order rows within each window
    [ROWS/RANGE frame]        <- which rows within the window to include
)

See the difference immediately:

-- GROUP BY: 6 rows out
SELECT category_id, AVG(unit_price) AS avg_price
FROM products GROUP BY category_id;

-- Window function: all 18 rows out, each with its category average attached
SELECT
    product_name,
    category_id,
    unit_price,
    AVG(unit_price) OVER (PARTITION BY category_id)            AS category_avg,
    ROUND(unit_price - AVG(unit_price) OVER (PARTITION BY category_id), 2) AS diff_from_avg
FROM products
ORDER BY category_id, unit_price DESC;

Result:

product_name category_id unit_price category_avg diff_from_avg
WorkStation X17 1 2450.00 1311.75 1138.25
UltraBook Pro 14 1 1499.00 1311.75 187.25
UltraBook Air 13 1 999.00 1311.75 -312.75
Legacy Netbook 10 1 299.00 1311.75 -1012.75

[!NOTE] 📌 That is the magic. Every product keeps its own row and knows its category’s average. Doing this without window functions requires a self-join or a correlated subquery — more code, slower, harder to read.

🔀 Window functions require MySQL 8.0+. In MySQL 5.7 and earlier they do not exist at all; you must imitate them with complicated workarounds. This alone is a strong reason to upgrade.

33.2 🏅 Ranking functions

Function Behaviour with ties Example: 100, 90, 90, 80
ROW_NUMBER() Always unique; tied rows get different numbers in no guaranteed order 1, 2, 3, 4
RANK() Ties share a rank, then it skips 1, 2, 2, 4
DENSE_RANK() Ties share a rank, no skip 1, 2, 2, 3
NTILE(n) Splits rows into n roughly equal buckets 4 buckets = quartiles
PERCENT_RANK() Relative rank as 0 to 1 0, 0.33, 0.33, 1
CUME_DIST() Share of rows at or below this one 0.25, 0.75, 0.75, 1
-- ✅ Works in BOTH: see all four side by side
SELECT
    product_name,
    category_id,
    unit_price,
    ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS row_num,
    RANK()       OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS rnk,
    DENSE_RANK() OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS dense_rnk,
    NTILE(4)     OVER (ORDER BY unit_price DESC)                          AS price_quartile
FROM products
ORDER BY category_id, unit_price DESC;

[!TIP] 💡 Which one do I want?

  • “Give me exactly one row per group” → ROW_NUMBER()
  • “Olympic medals — two golds means no silver” → RANK()
  • “Price tiers where ties belong together” → DENSE_RANK()
  • “Split my customers into 4 equal spending groups” → NTILE(4)

33.3 🥇 The top-N-per-group pattern

The most-used window function pattern in the world. Learn it once, use it forever.

-- ✅ Works in BOTH: the single most expensive product in each category
WITH ranked AS (
    SELECT
        p.product_name,
        p.unit_price,
        c.category_name,
        ROW_NUMBER() OVER (PARTITION BY p.category_id ORDER BY p.unit_price DESC) AS rn
    FROM products p
    JOIN categories c ON c.category_id = p.category_id
)
SELECT category_name, product_name, unit_price
FROM ranked
WHERE rn = 1
ORDER BY unit_price DESC;

[!WARNING] ⚠️ You cannot filter a window function in WHERE. Window functions are computed after WHERE (they run at roughly the same stage as SELECT), so WHERE ROW_NUMBER() OVER (...) = 1 is a syntax error in both engines. You must wrap it in a CTE or derived table and filter outside. This catches everyone once.

-- ✅ Real-world: each customer's most recent order
WITH ranked_orders AS (
    SELECT
        o.*,
        ROW_NUMBER() OVER (PARTITION BY o.customer_id ORDER BY o.order_date DESC, o.order_id DESC) AS rn
    FROM orders o
)
SELECT c.full_name, r.order_id, r.order_date, r.status
FROM ranked_orders r
JOIN customers c ON c.customer_id = r.customer_id
WHERE r.rn = 1
ORDER BY r.order_date DESC;

[!TIP] 💡 Note the tiebreaker , o.order_id DESC. If a customer placed two orders on the same date, without a tiebreaker the result is unpredictable — you can get a different answer on different runs. Always make your ORDER BY inside ROW_NUMBER() fully deterministic.

33.4 ↔️ LAG and LEAD — looking at neighbouring rows

-- ✅ Works in BOTH: month-over-month revenue change
WITH monthly AS (
    SELECT
        YEAR(o.order_date)  AS yr,
        MONTH(o.order_date) AS mth,
        SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS revenue
    FROM orders o
    JOIN order_items oi ON oi.order_id = o.order_id
    WHERE o.status IN ('Delivered','Shipped')
    GROUP BY YEAR(o.order_date), MONTH(o.order_date)
)
SELECT
    yr, mth,
    ROUND(revenue, 2)                                          AS revenue,
    ROUND(LAG(revenue) OVER (ORDER BY yr, mth), 2)             AS prev_month,
    ROUND(revenue - LAG(revenue) OVER (ORDER BY yr, mth), 2)   AS change_amount,
    ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY yr, mth))
          / NULLIF(LAG(revenue) OVER (ORDER BY yr, mth), 0), 1) AS change_pct
FROM monthly
ORDER BY yr, mth;

[!NOTE] 📌 LAG(x) gives you the value of x from the previous row. LEAD(x) gives you the next row’s value. Both take optional arguments: LAG(revenue, 3, 0) means “3 rows back, and use 0 if there is no such row.”

-- 🟥 MSSQL — real-world: how many days between each customer's consecutive orders?
SELECT
    c.full_name,
    o.order_id,
    o.order_date,
    LAG(o.order_date) OVER (PARTITION BY o.customer_id ORDER BY o.order_date) AS prev_order_date,
    DATEDIFF(DAY,
        LAG(o.order_date) OVER (PARTITION BY o.customer_id ORDER BY o.order_date),
        o.order_date) AS days_since_last_order         -- 🟥 MSSQL
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
ORDER BY c.full_name, o.order_date;
-- 🟦 MySQL version: DATEDIFF(later, earlier), with no unit argument
SELECT
    c.full_name,
    o.order_id,
    o.order_date,
    LAG(o.order_date) OVER (PARTITION BY o.customer_id ORDER BY o.order_date) AS prev_order_date,
    DATEDIFF(o.order_date,
             LAG(o.order_date) OVER (PARTITION BY o.customer_id ORDER BY o.order_date))
        AS days_since_last_order
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
ORDER BY c.full_name, o.order_date;

[!IMPORTANT] 🎯 LAG/LEAD real-world uses: month-over-month growth, time between events, detecting gaps in sequences, finding price changes, and spotting customers who have stopped buying (churn).

33.5 🎬 FIRST_VALUE, LAST_VALUE, NTH_VALUE

-- ✅ Works in BOTH
SELECT
    c.full_name,
    o.order_id,
    o.order_date,
    FIRST_VALUE(o.order_date) OVER (
        PARTITION BY o.customer_id ORDER BY o.order_date
    ) AS first_ever_order,
    LAST_VALUE(o.order_date) OVER (
        PARTITION BY o.customer_id ORDER BY o.order_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING   -- 🔑 essential!
    ) AS most_recent_order
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
ORDER BY c.full_name, o.order_date;

[!WARNING] ⚠️ The LAST_VALUE gotcha that trips up everyone. With ORDER BY present, the default frame (explained in 33.6, just below) is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW — so “last value” means “last value so far”, which is just the current row. You must explicitly widen the frame to UNBOUNDED FOLLOWING to get the true last value. FIRST_VALUE works as expected because the frame already starts at the beginning.

33.6 📏 Window frames explained

The frame decides which rows inside the window the function actually sees.

ROWS BETWEEN <start> AND <end>

Options:
  UNBOUNDED PRECEDING   ← the first row of the partition
  n PRECEDING           ← n rows before the current row
  CURRENT ROW
  n FOLLOWING           ← n rows after the current row
  UNBOUNDED FOLLOWING   ← the last row of the partition
Frame Meaning Use for
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW Everything up to here Running total
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW This row and the 2 before 3-period moving average
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING Neighbours on both sides Smoothing
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING The whole partition Partition totals
(no frame, no ORDER BY) The whole partition AVG() OVER (PARTITION BY x)
(no frame, with ORDER BY) ⚠️ Defaults to RANGE … CURRENT ROW Silently makes it a running calculation

[!WARNING] ⚠️ ROWS vs RANGE. ROWS counts physical rows. RANGE groups rows with equal ORDER BY values together. If two rows share the same date, RANGE includes both in the frame while ROWS does not. ROWS is what people usually mean — prefer ROWS unless you specifically want rows with equal values treated as one group.

33.7 🧪 Try it yourself

  1. Show every product with its category’s average, minimum, and maximum price alongside.
  2. Rank customers by lifetime spend using all three ranking functions and explain the differences you see.
  3. Find each customer’s most recent order using ROW_NUMBER().
  4. Show month-over-month revenue change with a percentage.
  5. Try filtering ROW_NUMBER() in WHERE, read the error, then fix it with a CTE.

🧭 In practice — window functions

How to use it. Append OVER (PARTITION BY ... ORDER BY ...) to a function. PARTITION BY restarts the calculation per group; ORDER BY defines the sequence within it. Unlike GROUP BY, the detail rows are kept — you get the per-row value and the summary side by side. Expected result: one output row per input row, each carrying a value computed across its window.

When to use it. Whenever you need a row and its context: this order plus the customer’s running total, this product plus its share of the category, this month plus the previous month.

Where to use it. Analytics and dashboards. Scenario: “each product’s price as a percentage of its category total” needs both the product row and the category sum. GROUP BY would collapse the products away; SUM(unit_price) OVER (PARTITION BY category_id) keeps them and attaches the total.

When not to use it. Window functions cannot appear in a WHERE or HAVING clause — they are computed at step 5, after filtering. To filter on a window result (“only rank 1”), wrap the query in a CTE or subquery and filter outside. Also avoid them where a plain GROUP BY answers the question: they do more work, because they retain every row.

Best practices. Be explicit about the frame when using a running aggregate. The default frame with an ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which groups ties together — so a running total over a column with duplicate values jumps in steps rather than row by row. Write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW when you mean row by row. Index the PARTITION BY and ORDER BY columns; window functions sort, and an index can remove that sort.


34. Ranking, running totals, and moving averages

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡 Intermediate 40 min Build running totals and moving averages · Work out percentages of a total · Find streaks and gaps · Measure medians and percentiles

[!NOTE] 📌 In plain words: This chapter is a cookbook. Every recipe here is a question a real business asks, with the query that answers it.

🌍 Analogy: A running total is a bank statement’s balance column: each line shows the new amount and everything so far. A moving average is judging your weight by the last seven days instead of by today alone.

34.1 📈 Running totals (cumulative sums)

-- ✅ Works in BOTH: revenue accumulating through the year
WITH daily AS (
    SELECT
        o.order_date,
        SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS day_revenue
    FROM orders o
    JOIN order_items oi ON oi.order_id = o.order_id
    WHERE o.status IN ('Delivered','Shipped')
    GROUP BY o.order_date
)
SELECT
    order_date,
    ROUND(day_revenue, 2) AS day_revenue,
    ROUND(SUM(day_revenue) OVER (
        ORDER BY order_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ), 2) AS running_total,
    ROUND(AVG(day_revenue) OVER (
        ORDER BY order_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ), 2) AS running_average
FROM daily
ORDER BY order_date;
-- ✅ Running total PER CUSTOMER — each customer's own accumulating spend
SELECT
    c.full_name,
    o.order_date,
    ROUND(ot.order_value, 2) AS order_value,
    ROUND(SUM(ot.order_value) OVER (
        PARTITION BY o.customer_id
        ORDER BY o.order_date, o.order_id
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ), 2) AS lifetime_to_date
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
JOIN (
    SELECT order_id, SUM(unit_price * quantity * (1 - discount)) AS order_value
    FROM order_items GROUP BY order_id
) ot ON ot.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
ORDER BY c.full_name, o.order_date;

34.2 📉 Moving averages

-- ✅ Works in BOTH: a 3-period moving average smooths out noise
WITH monthly AS (
    SELECT
        YEAR(o.order_date) * 100 + MONTH(o.order_date) AS ym,
        SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS revenue
    FROM orders o
    JOIN order_items oi ON oi.order_id = o.order_id
    WHERE o.status IN ('Delivered','Shipped')
    GROUP BY YEAR(o.order_date) * 100 + MONTH(o.order_date)
)
SELECT
    ym,
    ROUND(revenue, 2) AS revenue,
    ROUND(AVG(revenue) OVER (
        ORDER BY ym ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
    ), 2) AS moving_avg_3,
    ROUND(AVG(revenue) OVER (
        ORDER BY ym ROWS BETWEEN 5 PRECEDING AND CURRENT ROW
    ), 2) AS moving_avg_6
FROM monthly
ORDER BY ym;

[!IMPORTANT] 🎯 When to use a moving average: any time raw daily or monthly numbers are too noisy to see the trend. Stock prices, website traffic, sales, server load — smoothing reveals the direction.

34.3 🥧 Percentage of total

-- ✅ Works in BOTH: each category's share of revenue
WITH category_revenue AS (
    SELECT
        c.category_name,
        SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS revenue
    FROM categories c
    JOIN products p     ON p.category_id = c.category_id
    JOIN order_items oi ON oi.product_id = p.product_id
    JOIN orders o       ON o.order_id = oi.order_id
    WHERE o.status IN ('Delivered','Shipped')
    GROUP BY c.category_name
)
SELECT
    category_name,
    ROUND(revenue, 2) AS revenue,
    ROUND(100.0 * revenue / SUM(revenue) OVER (), 2) AS pct_of_total,
    ROUND(SUM(revenue) OVER (ORDER BY revenue DESC
          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), 2) AS cumulative_revenue,
    ROUND(100.0 * SUM(revenue) OVER (ORDER BY revenue DESC
          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
          / SUM(revenue) OVER (), 2) AS cumulative_pct
FROM category_revenue
ORDER BY revenue DESC;

[!TIP] 💡 SUM(revenue) OVER () — an empty OVER() means “the whole result set”. That gives you the grand total on every row, so you can compute percentages without a second query or a self-join. This is one of the most useful three characters in SQL.

[!IMPORTANT] 🎯 The cumulative_pct column is a Pareto analysis (also called ABC analysis) — “which 20% of categories produce 80% of revenue?” Retailers, warehouses, and finance teams ask for exactly this.

34.4 🔍 Finding gaps and islands

A classic problem. An island is an unbroken run of consecutive values — for example, orders on three days in a row. A gap is a hole in a sequence — for example, order numbers that were skipped.

-- ✅ Works in BOTH: find gaps in the order_id sequence
WITH ordered AS (
    SELECT
        order_id,
        LEAD(order_id) OVER (ORDER BY order_id) AS next_id
    FROM orders
)
SELECT
    order_id + 1 AS gap_starts,
    next_id  - 1 AS gap_ends,
    next_id - order_id - 1 AS missing_count
FROM ordered
WHERE next_id - order_id > 1;
-- 🟥 MSSQL: find runs of consecutive daily activity ("islands")
WITH active_days AS (
    SELECT DISTINCT order_date FROM orders
),
grouped AS (
    SELECT
        order_date,
        DATEADD(DAY, -ROW_NUMBER() OVER (ORDER BY order_date), order_date) AS grp  -- 🟥 MSSQL
    FROM active_days
)
SELECT
    MIN(order_date) AS streak_start,
    MAX(order_date) AS streak_end,
    COUNT(*)        AS consecutive_days
FROM grouped
GROUP BY grp
HAVING COUNT(*) > 1
ORDER BY streak_start;
-- 🟦 MySQL: the same trick, with DATE_SUB
WITH active_days AS (
    SELECT DISTINCT order_date FROM orders
),
grouped AS (
    SELECT
        order_date,
        DATE_SUB(order_date, INTERVAL ROW_NUMBER() OVER (ORDER BY order_date) DAY) AS grp
    FROM active_days
)
SELECT
    MIN(order_date) AS streak_start,
    MAX(order_date) AS streak_end,
    COUNT(*)        AS consecutive_days
FROM grouped
GROUP BY grp
HAVING COUNT(*) > 1
ORDER BY streak_start;

[!NOTE] 📌 The trick: subtract the row number from the date. For consecutive dates, that difference is constant, so grouping by it isolates each run. It looks like magic the first time; work through three rows by hand and it becomes obvious. The same pattern finds attendance streaks, periods when a system stayed online, consecutive login days, and shift schedules.

34.5 📊 Cohort and retention analysis

A cohort is a group of customers who started in the same month. Retention asks: how many of them are still buying one, two, three months later?

-- ✅ Works in BOTH: group customers by the month of their FIRST order, then track their activity
WITH first_order AS (
    SELECT
        customer_id,
        MIN(order_date) AS cohort_date
    FROM orders
    GROUP BY customer_id
),
activity AS (
    SELECT
        f.customer_id,
        YEAR(f.cohort_date) * 100 + MONTH(f.cohort_date) AS cohort_month,
        YEAR(o.order_date)  * 100 + MONTH(o.order_date)  AS activity_month
    FROM first_order f
    JOIN orders o ON o.customer_id = f.customer_id
)
SELECT
    cohort_month,
    activity_month,
    COUNT(DISTINCT customer_id) AS active_customers
FROM activity
GROUP BY cohort_month, activity_month
ORDER BY cohort_month, activity_month;

34.6 🎯 Deduplication with ROW_NUMBER

-- ✅ Works in BOTH: find (and delete) duplicate customers by email

-- Step 1: LOOK at what you would delete
WITH dupes AS (
    SELECT
        customer_id,
        email,
        ROW_NUMBER() OVER (PARTITION BY email ORDER BY customer_id) AS rn
    FROM customers
)
SELECT * FROM dupes WHERE rn > 1;

-- Step 2: delete all but the first of each group
WITH dupes AS (
    SELECT
        customer_id,
        ROW_NUMBER() OVER (PARTITION BY email ORDER BY customer_id) AS rn
    FROM customers
)
DELETE FROM customers
WHERE customer_id IN (SELECT customer_id FROM dupes WHERE rn > 1);
-- 🟥 MSSQL can DELETE directly from the CTE — very neat
WITH dupes AS (
    SELECT ROW_NUMBER() OVER (PARTITION BY email ORDER BY customer_id) AS rn
    FROM customers
)
DELETE FROM dupes WHERE rn > 1;

[!WARNING] ⚠️ Always run the SELECT version first. Deduplication deletes real customer records. ORDER BY customer_id decides which copy survives — think about whether you want the oldest, the newest, or the most complete row.

34.7 📐 Percentiles, medians, and distribution

[!NOTE] 📌 In plain words: An average can mislead when a few values are extreme. One €50,000 order pulls the average far above what a typical customer actually spends. The median (the middle value) and percentiles (P90 = the value that 90% of orders are below) describe your data much more honestly.

-- 🟥 MSSQL: median and P90 of order values
WITH order_totals AS (
    SELECT o.order_id,
           SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS order_value
    FROM orders o
    JOIN order_items oi ON oi.order_id = o.order_id
    GROUP BY o.order_id
)
SELECT DISTINCT
    CAST(PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY order_value) OVER () AS DECIMAL(10,2)) AS median_interpolated,
    CAST(PERCENTILE_DISC(0.50) WITHIN GROUP (ORDER BY order_value) OVER () AS DECIMAL(10,2)) AS median_real_row,
    CAST(PERCENTILE_CONT(0.90) WITHIN GROUP (ORDER BY order_value) OVER () AS DECIMAL(10,2)) AS p90
FROM order_totals;

Result:

median_interpolated median_real_row p90
938.00 938.00 2430.41
Function Returns Use when
PERCENTILE_CONT(p) Works out a value between the two nearest rows (it interpolates) A statistical median. May be a value nobody actually paid
PERCENTILE_DISC(p) The first real row at or past that percentile You need an actual observed value

[!WARNING] ⚠️ Three traps with PERCENTILE_CONT. It is a window function, not an aggregate — there is no GROUP BY form, so it repeats the answer on every row and you need DISTINCT (or a subquery) to collapse it. It returns FLOAT, so cast to DECIMAL before displaying money. And WITHIN GROUP (ORDER BY …) is mandatory — that is what it takes the percentile of.

-- 🟥 Median per group: partition the window
SELECT DISTINCT
    c.category_name,
    CAST(PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY p.unit_price)
         OVER (PARTITION BY c.category_id) AS DECIMAL(10,2)) AS median_price
FROM products p
JOIN categories c ON c.category_id = p.category_id
ORDER BY c.category_name;

🔀 MySQL has no PERCENTILE_CONT. Compute the median with ROW_NUMBER and COUNT instead — the portable technique that also works on any older MSSQL version:

-- ✅ Works in BOTH: median without PERCENTILE_CONT
WITH ranked AS (
    SELECT unit_price,
           ROW_NUMBER() OVER (ORDER BY unit_price) AS rn,
           COUNT(*)     OVER ()                    AS total
    FROM products
)
SELECT AVG(unit_price) AS median_price
FROM ranked
WHERE rn IN (FLOOR((total + 1) / 2.0), FLOOR((total + 2) / 2.0));   -- handles odd and even counts
-- 249.00 — the same answer PERCENTILE_CONT(0.5) gives for products.unit_price

[!TIP] 💡 Why FLOOR((total+1)/2.0) and FLOOR((total+2)/2.0)? An odd count makes both expressions the same row (so AVG returns it unchanged), and an even count makes them the two middle rows (so AVG averages them). One expression, both cases, no CASE. The FLOOR(… / 2.0) is not decoration: MSSQL’s / truncates integers, but MySQL’s / returns a decimal — plain (total + 1) / 2 is 9.5 there, matches no row number, and MySQL silently returns 299.00 instead of the correct 249.00.

Where each row sits in the distribution:

-- ✅ Works in BOTH (MySQL 8.0+)
SELECT
    product_name,
    unit_price,
    CAST(PERCENT_RANK() OVER (ORDER BY unit_price) AS DECIMAL(5,3)) AS pct_rank,
    CAST(CUME_DIST()    OVER (ORDER BY unit_price) AS DECIMAL(5,3)) AS cumulative_dist,
    NTILE(4)            OVER (ORDER BY unit_price)                  AS price_quartile
FROM products
ORDER BY unit_price DESC;

[!TIP] 💡 Cast, do not ROUND. PERCENT_RANK and CUME_DIST return FLOAT, and ROUND on a float still prints as 0.94099999999999995 in some clients. Casting to DECIMAL fixes the display for good.

Result (top rows):

product_name unit_price pct_rank cumulative_dist price_quartile
WorkStation X17 2450.00 1.000 1.000 4
UltraBook Pro 14 1499.00 0.941 0.944 4
UltraBook Air 13 999.00 0.882 0.889 4
Zenith Phone 12 899.00 0.824 0.833 4
VisionPanel 32 4K 749.00 0.706 0.778 3
Function Answers
PERCENT_RANK() “What fraction of rows are strictly below this one?” — always starts at 0
CUME_DIST() “What fraction of rows are at or below this one?” — always ends at 1
NTILE(n) “Which of n equal-sized buckets does this row fall in?”

[!TIP] 💡 NTILE divides by row count, not by value. Four quartiles of 18 products give buckets of 5, 5, 4, 4 rows — regardless of whether the prices cluster. If you need buckets by value range (€0–500, €500–1000 …), that is a CASE expression, not NTILE.

[!IMPORTANT] 🎯 Report the median and P90, not just the average. “Average response time 200 ms” hides that one user in ten waits two seconds. P90 and P99 are what your users actually experience, which is why every SLA (a service-level agreement — a promised speed or uptime) is written in percentiles.

34.8 🪟 Naming a window you reuse

Repeating a long OVER (…) clause three times is noise, and it is a place for a typo to hide.

-- 🟥 MSSQL 2022+ · 🟦 MySQL 8.0+: define the window once
SELECT
    product_name,
    unit_price,
    RANK()      OVER w AS price_rank,
    CUME_DIST() OVER w AS cumulative_dist,          -- not "cume_dist": a reserved word in MySQL
    LEAD(unit_price) OVER w AS next_cheapest        -- LEAD: the window is sorted most-expensive first
FROM products
WINDOW w AS (ORDER BY unit_price DESC)
ORDER BY unit_price DESC;

[!WARNING] ⚠️ The WINDOW clause sits between HAVING and ORDER BY, and it arrived in SQL Server only in 2022. On earlier versions, repeat the OVER (…) clause — or move it into a CTE. MySQL has had it since 8.0.

34.9 🧪 Try it yourself

  1. Build a running total of revenue by month for 2026.
  2. Add a 3-month moving average and compare the two lines.
  3. Compute each product’s share of its category’s revenue.
  4. Do a Pareto analysis: which products make up the first 80% of revenue?
  5. Find any gaps in the order_id sequence.
  6. Find each customer’s longest streak of consecutive months with an order.

🧭 In practice — ranking, running totals, and moving averages

How to use it. ROW_NUMBER() numbers rows uniquely; RANK() leaves gaps after ties; DENSE_RANK() does not. Running totals use SUM(...) OVER (ORDER BY ... ROWS UNBOUNDED PRECEDING); moving averages use AVG(...) OVER (ORDER BY ... ROWS BETWEEN 2 PRECEDING AND CURRENT ROW). LAG/LEAD reach to the previous or next row. Expected result: trend and ranking columns computed in the database, not in a spreadsheet.

When to use it. Leaderboards, month-on-month comparisons, cumulative revenue, smoothing noisy daily figures, and finding gaps or streaks in sequences.

Where to use it. Business reporting. Scenario: “each customer’s average days between orders” is LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) and then averaging the differences — and customers with a single order correctly produce NULL rather than a misleading zero.

When not to use it. Do not use RANK() when you need exactly one row per group — ties give you two rank-1 rows and your “top product per category” query returns more rows than categories. ROW_NUMBER() with a deterministic tiebreaker is what you want. Do not compute a moving average over data with missing days without first joining to a calendar table, or the window averages the wrong number of periods.

Best practices. Always give ranking an ORDER BY that cannot tie, or accept that the winner is arbitrary and may change between runs. Be deliberate about ROWS versus RANGE — see the frame note in Chapter 33; it is the most common source of a running total that looks almost right. For gaps-and-islands problems (streaks of consecutive months), the standard trick is the difference between a row number and the date sequence.


35. PIVOT and UNPIVOT

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟡 Intermediate 20 min Turn rows into columns for spreadsheet-style reports · Turn columns back into rows · Know when to pivot outside SQL

[!NOTE] 📌 In plain words: Pivoting turns rows into columns. Instead of 12 rows (one per month), you get 1 row with 12 month columns — the shape every spreadsheet report wants.

🌍 Analogy: A tall thin list of “month, amount” pairs versus a wide table with a column per month. Same data, rotated 90 degrees.

35.1 🔄 The portable way: CASE (works everywhere)

-- ✅ Works in BOTH — and this is the version you should usually write
SELECT
    c.category_name,
    ROUND(SUM(CASE WHEN MONTH(o.order_date) = 1 THEN oi.unit_price*oi.quantity*(1-oi.discount) ELSE 0 END), 2) AS jan,
    ROUND(SUM(CASE WHEN MONTH(o.order_date) = 2 THEN oi.unit_price*oi.quantity*(1-oi.discount) ELSE 0 END), 2) AS feb,
    ROUND(SUM(CASE WHEN MONTH(o.order_date) = 3 THEN oi.unit_price*oi.quantity*(1-oi.discount) ELSE 0 END), 2) AS mar,
    ROUND(SUM(CASE WHEN MONTH(o.order_date) = 4 THEN oi.unit_price*oi.quantity*(1-oi.discount) ELSE 0 END), 2) AS apr,
    ROUND(SUM(CASE WHEN MONTH(o.order_date) = 5 THEN oi.unit_price*oi.quantity*(1-oi.discount) ELSE 0 END), 2) AS may,
    ROUND(SUM(CASE WHEN MONTH(o.order_date) = 6 THEN oi.unit_price*oi.quantity*(1-oi.discount) ELSE 0 END), 2) AS jun,
    ROUND(SUM(oi.unit_price*oi.quantity*(1-oi.discount)), 2) AS total
FROM categories c
JOIN products p     ON p.category_id = c.category_id
JOIN order_items oi ON oi.product_id = p.product_id
JOIN orders o       ON o.order_id = oi.order_id
WHERE o.status IN ('Delivered','Shipped') AND YEAR(o.order_date) = 2026
GROUP BY c.category_name
ORDER BY total DESC;

[!TIP] 💡 This SUM(CASE …) approach (called conditional aggregation) is readable and works in every SQL database on earth. MSSQL’s own PIVOT syntax is shorter, but it only works in SQL Server and becomes harder to read as soon as you need two totals.

35.2 🟥 MSSQL PIVOT syntax

-- 🟥 MSSQL only
SELECT category_name, [1] AS jan, [2] AS feb, [3] AS mar, [4] AS apr, [5] AS may, [6] AS jun
FROM (
    SELECT
        c.category_name,
        MONTH(o.order_date) AS order_month,
        oi.unit_price * oi.quantity * (1 - oi.discount) AS line_total
    FROM categories c
    JOIN products p     ON p.category_id = c.category_id
    JOIN order_items oi ON oi.product_id = p.product_id
    JOIN orders o       ON o.order_id = oi.order_id
    WHERE o.status IN ('Delivered','Shipped') AND YEAR(o.order_date) = 2026
) AS src
PIVOT (
    SUM(line_total)
    FOR order_month IN ([1],[2],[3],[4],[5],[6])
) AS pvt
ORDER BY category_name;

[!WARNING] ⚠️ PIVOT has three real limitations: you must list the column values explicitly (you cannot pivot an unknown set of values without dynamic SQL), it supports one aggregate only, and every column the pivot does not mention is silently used for grouping — so one stray column in the source query produces confusing extra rows. Always build the source as a subquery in FROM that contains only the three columns you need.

35.3 🔃 UNPIVOT — columns back into rows

-- 🟥 MSSQL
SELECT product_name, metric_name, metric_value
FROM (
    SELECT
        product_name,
        -- 🔑 every unpivoted column MUST share one data type
        CAST(unit_price     AS DECIMAL(12,2)) AS unit_price,
        CAST(units_in_stock AS DECIMAL(12,2)) AS units_in_stock,
        CAST(reorder_level  AS DECIMAL(12,2)) AS reorder_level
    FROM products
) AS src
UNPIVOT (
    metric_value FOR metric_name IN (unit_price, units_in_stock, reorder_level)
) AS unpvt
ORDER BY product_name, metric_name;

[!WARNING] ⚠️ The CAST is not optional, and this is the error everyone hits first. UNPIVOT collapses several columns into one output column, so they must all have the same data type. In products, unit_price is DECIMAL(10,2) while units_in_stock and reorder_level are INT. Without the casts you get:

Msg 8167: The type of column "units_in_stock" conflicts with the type
          of other columns specified in the UNPIVOT list.

Cast every column to the widest type in the set — here DECIMAL(12,2), which holds both the prices and the counts without losing anything.

-- ✅ Works in BOTH: the portable UNPIVOT with UNION ALL
SELECT product_name, 'unit_price'     AS metric, unit_price     AS value FROM products
UNION ALL
SELECT product_name, 'units_in_stock',           units_in_stock         FROM products
UNION ALL
SELECT product_name, 'reorder_level',            reorder_level          FROM products
ORDER BY product_name, metric;

[!IMPORTANT] 🎯 When you need UNPIVOT: normalizing a badly designed table that has jan_sales, feb_sales, mar_sales… columns into a proper (month, sales) structure. Wide tables like that are a sign of poor table design — see Chapter 51.

35.4 🔀 Dynamic pivoting — when the columns are not known in advance

When you do not know the column names in advance, you must build the query’s text while the code runs, then execute that text. This is called dynamic SQL.

-- 🟥 MSSQL: build the column list at runtime, then execute
DECLARE @cols   NVARCHAR(MAX);
DECLARE @sql    NVARCHAR(MAX);

SELECT @cols = STRING_AGG(QUOTENAME(category_name), ',')
FROM (SELECT DISTINCT category_name FROM categories) AS c;

SET @sql = N'
SELECT order_month, ' + @cols + N'
FROM (
    SELECT MONTH(o.order_date) AS order_month,
           c.category_name,
           oi.unit_price * oi.quantity * (1 - oi.discount) AS line_total
    FROM orders o
    JOIN order_items oi ON oi.order_id = o.order_id
    JOIN products p     ON p.product_id = oi.product_id
    JOIN categories c   ON c.category_id = p.category_id
    WHERE o.status IN (''Delivered'',''Shipped'')
) AS src
PIVOT (SUM(line_total) FOR category_name IN (' + @cols + N')) AS pvt
ORDER BY order_month;';

EXEC sp_executesql @sql;

[!WARNING] ⚠️ QUOTENAME() is doing security work here. It safely wraps each identifier in brackets so a category named x]; DROP TABLE orders;-- cannot break out. Never build dynamic SQL by concatenating raw values — see Chapter 55.

[!TIP] 💡 Honestly: pivot in your reporting tool when you can. Excel, Power BI, Tableau, pandas, and every BI tool pivot natively, handle unknown column sets effortlessly, and do not require dynamic SQL. Pivot in SQL when SQL is the last stop — a CSV export, a stored procedure feeding a fixed report.

35.5 🧪 Try it yourself

  1. Build a table of units sold per product per quarter, quarters as columns.
  2. Produce a customer-count-by-country-and-tier cross-tab.
  3. Unpivot the products price/stock/reorder columns into rows.
  4. Write the monthly revenue pivot with CASE and, in MSSQL, with PIVOT. Which would you rather maintain?

🧭 In practice — PIVOT and UNPIVOT

How to use it. The portable way is conditional aggregation: SUM(CASE WHEN month = 1 THEN amount END) AS jan, repeated per column. SQL Server also has a dedicated PIVOT operator. Both need the output columns listed in advance. Expected result: rows rotated into columns — the shape every spreadsheet report wants.

When to use it. When a human will read the output as a grid: months across the top, categories down the side.

Where to use it. Management reports and exports. Scenario: a twelve-column revenue-by-month report. The CASE version works identically on both engines and is the one to reach for; it is also easier to read six months later than the PIVOT syntax.

When not to use it. Do not pivot when the set of columns is unknown or changes — that forces dynamic SQL (Chapter 59), which brings an injection risk and a query nobody can read. Do not pivot at all if the consumer is Excel, Power BI, or a reporting tool: they all pivot natively, they do it interactively, and doing it in SQL freezes a choice the user would rather make themselves.

Best practices. Prefer the CASE form over the PIVOT operator: it is portable, it composes with everything else, and it does not have PIVOT’s implicit-grouping behaviour, where every column you did not mention silently becomes part of the grouping and splits your rows. If you must pivot dynamically, parameterise everything and quote identifiers with QUOTENAME — never concatenate raw names.


✅ Checkpoint — after Chapter 35 · you can answer real business questions

[!IMPORTANT] Joins and window functions are the two skills that separate someone who can retrieve data from someone who can answer questions with it.

🗣️ Teach it back

What is it? Why does it matter? How does it work? Can I give an example? — for each of:

  • INNER versus LEFT JOIN, and what an outer join is for (Ch 28)
  • Row multiplication — why a join can inflate a total (Ch 28)
  • EXISTS versus IN versus a join (Ch 30)
  • CTEs, including recursive ones (Ch 31)
  • Window functions, and how they differ from GROUP BY (Ch 33–34)
🧪 Self-check questions
  1. How do you find customers who have never placed an order?
  2. You add a condition on the right-hand table of a LEFT JOIN and your outer join stops behaving like one. What happened?
  3. Why does NOT IN (SELECT ...) sometimes return no rows at all?
  4. What does a window function give you that GROUP BY cannot?
  5. Your “top product per category” query returns more rows than there are categories. What is the likely cause?
  6. Total revenue jumped when you joined orders to order_items. Why?
📝 Sample answers
  1. LEFT JOIN from customers to orders, then WHERE o.order_id IS NULL. The outer join keeps every customer and fills the order columns with NULL when there is no match, so testing for NULL isolates exactly the non-matches. NOT EXISTS is the other idiomatic way. This pattern answers every “things without a matching thing” question.

  2. You put it in WHERE instead of ON. A WHERE condition on the right table is evaluated after the join, and NULL fails it — so the unmatched rows the outer join deliberately kept are thrown away again, turning it into an inner join. Move the condition into the ON clause.

  3. Because one of the subquery’s values is NULL. x NOT IN (1, 2, NULL) is unknown for every x, so nothing qualifies and you get an empty result rather than an error. NOT EXISTS is NULL-safe and is the correct tool. See Chapter 30.

  4. It keeps the detail rows. GROUP BY collapses rows into one per group; a window function computes across the group and attaches the answer to every row. That is what lets you show a product alongside its category total, or an order alongside the customer’s running balance.

  5. Ties. RANK() gives two rows rank 1 when they tie, so a WHERE rank = 1 filter returns both. Use ROW_NUMBER() with a tiebreaker column so the ordering is deterministic and exactly one row wins per group.

  6. Row multiplication. Each order row is repeated once per item, so summing the order-level total counts it several times. Aggregate at the right grain — sum the line amounts, or sum order totals from a subquery that has one row per order.

🎯 Give a simple example

Describe, in plain words, how you would produce “each customer’s total spend, their most recent order date, and how that compares with the previous order”. Say which chapter’s tool handles each of the three parts.


Part index Prerequisites Previous Next Full course