Query with SUM and CASE
SELECT region,
SUM(CASE WHEN channel = 'Web'
THEN amount_cents END) AS web_cents,
SUM(CASE WHEN channel = 'Store'
THEN amount_cents END) AS store_cents,
SUM(CASE WHEN channel = 'Partner'
THEN amount_cents END) AS partner_cents
FROM sales_pivot_demo
GROUP BY region
ORDER BY region;Set up the example data
Amounts are in cents so this demo uses exact whole-number sums. Row 4 is a refund of 200 cents. Rows 7 and 9 have an unknown amount, which does not mean a sale of zero. The categories are set by the report, not by whichever rows happen to exist today.
CREATE TABLE sales_pivot_demo (
id INTEGER PRIMARY KEY,
region TEXT NOT NULL,
channel TEXT NOT NULL,
amount_cents INTEGER
);
INSERT INTO sales_pivot_demo VALUES
(1, 'North', 'Web', 1200),
(2, 'North', 'Web', 300),
(3, 'North', 'Store', 700),
(4, 'North', 'Web', -200),
(5, 'South', 'Web', 900),
(6, 'South', 'Partner', 400),
(7, 'South', 'Partner', NULL),
(8, 'East', 'Store', 500),
(9, 'West', 'Partner', NULL);Download the full example (.sql)
The download uses an empty SQLite database with the same data and queries as this guide. Run it once on a test connection. The course's teaching editor has a limited engine, so run this script in SQLite rather than in the course lab.
Before changing the shape, look at the summary in long format. It is a handy reference for checking each cell of the grid:
SELECT region, channel, SUM(amount_cents) AS known_amount
FROM sales_pivot_demo
GROUP BY region, channel
ORDER BY region, channel;Summary before pivot
| region | channel | known_amount |
|---|---|---|
| This | Store | 500 |
| North | Store | 700 |
| North | Web | 1300 |
| West | Partner | NULL |
| South | Partner | 400 |
| South | Web | 900 |
Verified grid: known amounts in cents
| region | web_cents | store_cents | partner_cents |
|---|---|---|---|
| East | NULL | 500 | NULL |
| North | 1300 | 700 | NULL |
| West | NULL | NULL | NULL |
| South | 900 | NULL | 400 |
For the Web column, CASE returns the amount of each Web transaction and NULL for the rest. SUM combines those contributions within each region. North holds 1200 + 300 − 200 = 1300; using MAX to “remove repeats” would return 1200 and answer a different question.
We group by region only. If you added channel to the GROUP BY, you would be back to one row per region and channel, with mostly empty columns. If you added id, you would keep one row per transaction and undo the summary. The grouping level must match the report's layout.
The known cells add up to 3800 cents, the same as SUM(amount_cents) over these nine rows. That check confirms no known amounts were lost or multiplied. It does not make the two NULL values known: the final financial total still needs them resolved.
How it works
From a long list to a report grid
At the source, each transaction has a region, a channel and an amount. The report wants one row per region and three columns: Web, Store and Partner. The channel stops repeating down the rows and moves into the header.
That transformation does not mean you should store the table that way. One physical column per channel makes adding categories and querying the set harder. Normally keep the source in long format and produce the grid when you query or export the report.
The three parts of this pivot
| Part | Choice | Consequence |
|---|---|---|
| Final row | region | One row per region |
| Columns | channel | Web, Store and Partner |
| Measure | SUM(amount_cents) | The transactions in each cell are added up |
If you already know SUM with CASE, here we apply it to a problem about the shape of the result. Changing the headers is not enough: the aggregate must keep the meaning of the data.
NULL does not always mean “no sales”
In the grid, North/Partner has no transactions; West/Partner has one, but its amount is unknown. Both cells come out NULL. South/Partner shows 400 because SUM ignores the NULL amount of the second transaction: it is a known subtotal, not a claim that both add up to exactly 400.
To tell missing records apart from pending amounts, also keep a count of transactions and a count of known values:
WITH regions(region) AS (VALUES ('North'), ('West'))
SELECT r.region,
COUNT(v.id) AS partner_rows,
COUNT(v.amount_cents) AS known_amounts,
SUM(v.amount_cents) AS known_sum
FROM regions AS r
LEFT JOIN sales_pivot_demo AS v
ON v.region = r.region AND v.channel = 'Partner'
GROUP BY r.region
ORDER BY r.region;Two NULL cells with different causes
| region | partner_rows | known_amounts | known_sum |
|---|---|---|---|
| North | 0 | 0 | NULL |
| West | 1 | 0 | NULL |
COALESCE(SUM(...), 0) turns both situations into zero. That may be fine if the report treats every gap as zero and input amounts are never unknown. With our data it would hide West's pending transaction. Choose the presentation after deciding the meaning, not to make the table look fuller.
To include a region with no transactions, start from a list of every region and LEFT JOIN the source before grouping. A region cannot appear from a transactions table that holds none of its rows. Keep filters on the right-hand table in ON when every region must be kept.
Variations and limits
The same grid with PIVOT in SQL Server
In T-SQL, PIVOT expresses the change of shape with a dedicated operator. This version assumes a table with the same data and suitable types, such as int for amount_cents. SQLite's TEXT setup is not meant to be copied as SQL Server DDL.
SELECT region,
[Web] AS web_cents,
[Store] AS store_cents,
[Partner] AS partner_cents
FROM (
SELECT region, channel, amount_cents
FROM sales_pivot_demo
) AS source
PIVOT (
SUM(amount_cents)
FOR channel IN ([Web], [Store], [Partner])
) AS matrix
ORDER BY region;The source subquery selects exactly region, channel and amount. It leaves out id: columns that are neither the category nor the measure affect the pivot's grouping. Bringing the transaction id into the source can split the grid into several rows per region.
The IN list defines the columns the report returns. A new category does not create another column automatically. For more than one measure, such as amount and number of transactions, conditional aggregation usually expresses them together more clearly. Check the official PIVOT syntax (opens in a new tab) before adapting the operator.
New categories, dynamic pivots and lost detail
If a «Distribuidor» channel appears, the query will still return three columns, and that channel's amount will be left out even though the region still appears. Check the list of categories and reconcile the sums with the source; an «Others» column can make sense if the report defines one explicitly.
When the headers must follow the data, you have two options: return region/channel rows to the client and pivot them there, or build dynamic SQL. The first keeps the query's structure stable and lets a reporting tool handle the headers. In the second, the headers are SQL identifiers and cannot be passed as value parameters. Use an allow-list, the engine's identifier escaping and parameters for filters; never concatenate free text received from a user.
Do not confuse PIVOT with a transpose without aggregation. North/Web had three transactions; after the pivot only their sum remains. From that cell you can no longer tell which one was the refund or rebuild the three original rows. UNPIVOT can go back to a long format of cells, but it does not recover that detail. In SQL Server it also has specific behaviour with NULL; check whether you want to keep or drop empty cells.
Which pattern to use on each engine
Support for this approach
| Engine | Approach in this guide | What to check |
|---|---|---|
| SQLite | SUM(CASE ...) and GROUP BY | The full examples run here |
| PostgreSQL | Conditional aggregation; FILTER as an alternative | NULL, types and how the measure is aggregated |
| MySQL | SUM(CASE ...) and GROUP BY | ONLY_FULL_GROUP_BY and grouped columns |
| SQL Server | Conditional aggregation or PIVOT | Source projection and column list |
For real amounts, use the exact type and scale your model requires. Whole cents work when that is the unit and you need no further fractions; DECIMAL/NUMERIC may suit other currencies, taxes or calculations. Do not convert the sum to text before aggregating.
A pivot is not guaranteed to be faster than several CASE expressions. Cut the rows down with the right filters first, check that a JOIN has not multiplied the source and review the plan with EXPLAIN. Measure with representative data and your real categories; this small example demonstrates results, not performance.
Checking another calculation
SELECT region,
SUM(CASE WHEN channel = 'Web' THEN 1 ELSE 0 END) AS web_rows,
SUM(CASE WHEN channel = 'Store' THEN 1 ELSE 0 END) AS store_rows,
SUM(CASE WHEN channel = 'Partner' THEN 1 ELSE 0 END) AS partner_rows
FROM sales_pivot_demo
GROUP BY region
ORDER BY region;Verified counts, including NULL amounts
| region | web_rows | store_rows | partner_rows |
|---|---|---|---|
| East | 0 | 1 | 0 |
| North | 3 | 1 | 0 |
| West | 0 | 0 | 1 |
| South | 1 | 0 | 2 |
South has two Partner transactions. CASE contributes one per transaction, whatever the amount. Counting amount_cents would drop the unknown value and give a different figure.