SQL to pivot rows into columns
Turn row values into columns using conditional aggregation.
SELECT
product,
SUM(CASE WHEN quarter = 'Q1' THEN amount ELSE 0 END) AS q1,
SUM(CASE WHEN quarter = 'Q2' THEN amount ELSE 0 END) AS q2,
SUM(CASE WHEN quarter = 'Q3' THEN amount ELSE 0 END) AS q3,
SUM(CASE WHEN quarter = 'Q4' THEN amount ELSE 0 END) AS q4
FROM sales
GROUP BY product;How to pivot rows to columns
Pivoting reshapes long data (one row per category) into wide data (one column per category). Conditional aggregation works in every dialect.
How it works
- Each CASE expression keeps only the amount for one quarter and zeroes out the rest.
- SUM collapses those per-quarter values into a single row per product.
- GROUP BY product produces one output row per product, with a column per quarter.
- SQL Server also has a dedicated PIVOT operator, but conditional aggregation is the portable choice.
Related SQL queries
- SQL to count rows per group
- SQL to group by month
- SQL to calculate a running total
- SQL to find duplicate rows
- SQL to delete duplicate rows (keep one)
- SQL to find the second highest value
Frequently asked questions
How do I pivot rows to columns in SQL?
Pivoting reshapes long data (one row per category) into wide data (one column per category). Conditional aggregation works in every dialect. Each CASE expression keeps only the amount for one quarter and zeroes out the rest. SUM collapses those per-quarter values into a single row per product. GROUP BY product produces one output row per product, with a column per quarter. SQL Server also has a dedicated PIVOT operator, but conditional aggregation is the portable choice.
Does this work in PostgreSQL, MySQL, SQL Server, and SQLite?
Yes — this query uses standard SQL that runs unchanged on PostgreSQL, MySQL, SQL Server, and SQLite.
Can I generate this query for my own tables?
Yes. Describe what you want in plain English with Forgly's free AI SQL Generator and it writes the query for your dialect.