Pivot tables: rows, columns and one measure
A pivot lays the same summary out as a grid. One field down the side, one across the top, one number in the middle — and two dimensions become comparable at a glance.
Three fields are the whole idea
The row field is the vertical key (region), the column field the horizontal one (channel), and the value field the number to compute (revenue). The aggregate is SUM, COUNT, AVG, MIN or MAX. Choose those three and the table's shape is fixed.
A pivot is GROUP BY with two keys, displayed differently. GROUP BY region, channel produces the same numbers as a list; the pivot folds the second key into columns for human comparison.
| Row | Column | Value (SUM) | Reading |
|---|---|---|---|
| Seoul | online | 12,400,000 | Seoul online revenue |
| Seoul | store | 8,100,000 | Seoul store revenue |
| Busan | online | 6,300,000 | Busan online revenue |
| Total | 26,800,000 | online total across regions |
Totals must be recomputed
Grand totals cannot be produced by adding cells when the aggregate is AVG: averaging cell averages loses the weights. Correct totals come from the original rows. QueryDeck computes row totals, column totals and the grand total in separate queries.
SUM and COUNT happen to add up from cells; AVG, MIN and MAX do not. Knowing this also lets you audit pivot totals from other tools.
SELECT region_id, channel, SUM(revenue) AS revenue
FROM orders
GROUP BY region_id, channel
ORDER BY region_id, channel;
What an empty cell means
An empty cell means no rows for that combination, which is not the same as zero. Filling it with zero distorts any average, so leave it blank and explain in a footnote.
Too many columns make the table scroll sideways. Above about ten column values, keep the largest and group the rest as Other.
When a pivot is the wrong tool
A row field with thousands of values (an order id) produces a meaningless grid. Pivots suit categories with ten or twenty values. For time series, keep dates as rows and use a line chart instead of turning months into columns.
Three checks on a pivot
First, the grand total should equal the total of the source table. Second, the sum of the row totals should equal the sum of the column totals. Third, confirm that an empty cell really is a combination with no rows. Pass those three and the numbers can be quoted.
With COUNT, check which column is being counted: COUNT(*) counts rows while COUNT(column) counts non-null values, so they differ wherever data is missing.
Questions
Pivot or GROUP BY?
Pivot when the result is meant to be compared as a grid; GROUP BY when further calculation or sorting follows. A pivot is a summary for reading.
Can a pivot use a calculated field?
Here you pick one value field. Create the calculated column in SQL first, then choose it as the value.
Sources
Every query in this guide runs against the built-in sample data.
Open the lab