SQL Guide · Prompt: “Summarize total revenue per region for Won deals in the pipeline table”
Pivot Rows to Columns in SQL with Conditional Aggregation
Verified by LiveFormulaLab Engineering Team • Updated November 2026
Turn row categories into cross-tab columns in standard ANSI SQL using conditional aggregation SUM(CASE WHEN). Works in Postgres, MySQL, and Snowflake.
Verified SQL Syntax
SELECT region, SUM(revenue) AS won_revenue
FROM pipeline
WHERE status = 'Won'
GROUP BY region;How This Formula Works (Step-by-Step)
Conditional aggregation with SUM(CASE WHEN ... THEN amount ELSE 0 END) works across every SQL dialect without proprietary PIVOT syntax.
Step 1: Group by your primary dimension (for example, quarter or rep).
Step 2: Create one SUM(CASE WHEN region = '...' THEN revenue ELSE 0 END) expression per output column.
Formula Syntax & Arguments Breakdown
Transforms vertical row categories into horizontal summary columns via conditional aggregation: SUM(CASE WHEN category = ... THEN amount ELSE 0 END).
| Argument / Clause | Requirement | Data Type | Role & Behavior |
|---|---|---|---|
SUM(CASE WHEN ... THEN revenue ELSE 0 END) | Required | Conditional Aggregate | Sums revenue selectively for one specific status, quarter, or plan into its own output column. |
GROUP BY region | Required | Row Dimension | Defines one summary row per region or account across the pivoted columns. |
WHERE status = 'Won' | Optional | Row Filter | Filters rows prior to conditional aggregation for faster execution. |
3 Real-World Use Cases
- Transforming normalized transaction rows into Q1, Q2, Q3, Q4 summary columns.
- Building funnel conversion matrices (Trial, Active, Churned) in one SQL view.
- Preparing clean executive KPI tables directly from raw warehouse logs.
Cross-Platform Equivalents
- Excel
=SUMIFS(D2:D6, B2:B6, "NA", C2:C6, "Won")- SQL
SELECT quarter, SUM(CASE WHEN region = 'NA' THEN revenue ELSE 0 END) AS na_rev, SUM(CASE WHEN region = 'EU' THEN revenue ELSE 0 END) AS eu_rev FROM pipeline WHERE status = 'Won' GROUP BY quarter;- Python Pandas
df[df['status'] == 'Won'].pivot_table(index='quarter', columns='region', values='revenue', aggfunc='sum', fill_value=0)
Common Mistakes & Pro Tips
Pitfalls & How to Fix Them
Mistake: Using COUNT(CASE WHEN status = 'Won' THEN 1 ELSE 0 END) counts every row because COUNT counts 0 as non-null!
Fix: Always use ELSE NULL (or omit ELSE) inside COUNT(CASE WHEN ... THEN 1 END), or use SUM(CASE WHEN ... THEN 1 ELSE 0 END).
Mistake: Forgetting ELSE 0 inside SUM(CASE...) causes regions with zero matching deals to display NULL instead of 0.
Fix: Include ELSE 0 inside SUM(CASE...) or wrap the aggregate in COALESCE(..., 0).
Mistake: Hardcoding dynamic high-cardinality values like hundreds of SKUs makes manual CASE pivoting unmaintainable.
Fix: Keep conditional CASE pivots for stable low-cardinality dimensions (Quarters, Plans, Statuses, Regions).
Engineering Pro Tips
- In PostgreSQL and DuckDB, use the cleaner ANSI FILTER syntax: SUM(revenue) FILTER (WHERE status = 'Won') AS won_revenue.
- Conditional aggregation is 100% portable across Postgres, MySQL, SQLite, Snowflake, BigQuery, and Redshift—unlike vendor-specific PIVOT.
- Divide two CASE aggregates in the same SELECT to compute conversion rates (Won / Total) in a single table scan.
Frequently Asked Questions
- Why prefer SUM(CASE WHEN) over database-specific PIVOT?
- CASE WHEN is 100% portable across PostgreSQL, MySQL, SQLite, BigQuery, and Snowflake.
- How do I pivot counts instead of sums?
- Use COUNT(CASE WHEN status = 'Won' THEN 1 END) or SUM(CASE WHEN status = 'Won' THEN 1 ELSE 0 END).
- Does PostgreSQL have a FILTER clause shortcut?
- Yes! In Postgres you can write SUM(revenue) FILTER (WHERE region = 'NA').
Related Formulas & Guides
- Build Customer First-Purchase Cohorts in SQL — Find each customer first purchase date and segment orders into cohorts in SQL using MIN() OVER (PARTITION BY) or GROUP BY.
- Handle NULL Values Cleanly in SQL with COALESCE — Replace NULL values cleanly with 0 or fallback text in SQL LEFT JOIN queries using COALESCE. Includes Excel and Pandas equivalents.
- How to Find Duplicate Rows in SQL Using GROUP BY — Find duplicate emails, IDs, or records in any SQL table using GROUP BY and HAVING COUNT(*) > 1. Test live in the interactive SQL sandbox.
- Calculate a Running Total in SQL Using Window Functions — Calculate a cumulative running total in PostgreSQL, Snowflake, or BigQuery with SUM() OVER (ORDER BY). Test and convert to Excel/Pandas.