SQL Intermediate Lesson 8: Pivot Reports With CASE

SQL Intermediate Lesson 8: Pivot Reports With CASE 1

πŸ“Ž This article includes 2 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ SQL Intermediate Course Β· Lesson 8 of 10

Advertisement
In this article
  1. Actual vs target
  2. Common mistakes
  3. Practice

Managers want reports with categories across the top. The portable way to pivot in SQL is conditional aggregation: a SUM of a CASE per column.

SELECT c.region,
       SUM(CASE WHEN o.status = 'Delivered' THEN o.qty * p.price ELSE 0 END) AS delivered,
       SUM(CASE WHEN o.status = 'Shipped'   THEN o.qty * p.price ELSE 0 END) AS shipped,
       SUM(CASE WHEN o.status = 'Pending'   THEN o.qty * p.price ELSE 0 END) AS pending
FROM orders o JOIN customers c USING (customer_id) JOIN products p USING (product_id)
GROUP BY c.region;

For counts, sum 1s: SUM(CASE WHEN ... THEN 1 ELSE 0 END). In SQLite, MySQL and PostgreSQL a true condition is 1, so SUM(mode = 'UPI') works too.

Actual vs target

WITH a AS (SELECT region, SUM(amount) AS actual FROM sales WHERE month = '2026-09' GROUP BY region)
SELECT t.region, a.actual, t.target, ROUND(100.0 * a.actual / t.target, 1) AS pct
FROM targets t LEFT JOIN a ON a.region = t.region
WHERE t.month = '2026-09';
πŸ’‘ SQL Server and Oracle have a PIVOT keyword, but CASE works everywhere and handles several measures at once. If the column list keeps changing, pivot in Excel or Power BI instead.

Common mistakes

  • Missing ELSE 0: a column with no matches shows NULL, and adding NULLs across gives NULL.
  • Hard-coding months that roll every year: generate the column list or pivot in the reporting tool.

Practice

Download shop2.db and this lesson’s exercise file below. Open the database in DB Browser for SQLite (free), paste each task into the Execute SQL tab and compare with the expected result printed under it. Answers are at the bottom of the file.

πŸ“Ž Practice files for this article

⬇ Download all 2 files (ZIP Β· 9 KB)

  • πŸ“„
    Practice database (SQLite)shop2.db: customers, products, 300 orders, payments, employees with managers and monthly targets.
    ⬇ DB Β· 48 KB
  • πŸ—ƒοΈ
    Lesson 8 exercisesTasks with the real expected result under each, and answers at the bottom.
    ⬇ SQL Β· 3 KB

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

Advertisement
✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong