MSBA-260 · Lesson 6 of 12 · 19 min
Pivoting and unpivoting
▶ Video coming soon A video version of this lesson is on the way.
The budget office sent Kwabena a spreadsheet of program targets that looked tidy on screen: one row per program, and one column per month from September to April, each holding the target headcount. It was easy to read and impossible to model. To compare targets with actual enrollment by month, Power BI needed one row per program per month with a single Target column. "Every report-friendly spreadsheet has to be turned on its side before a model can use it," Kwabena told Maribeth. "That's unpivoting."
This lesson covers the PL-300 objectives *pivot, unpivot, and transpose data*, *group and aggregate rows* and *convert semi-structured data to a table*. They share one idea: the shape of a table matters as much as its contents. Models work best with long, narrow tables, where each column holds one kind of value and each row is one observation. People often prefer wide tables, where categories run across the top. Power Query moves data between the two.
Wide and long
In the wide targets table, the month is hidden in the column headers. That causes three problems. A slicer cannot filter by month, because month is not a column. A new month means a new column, so the model changes shape every month. And a measure that sums targets has to name every column. In the long table, month is an ordinary column, the shape never changes, and one measure sums the Target column for whatever months are selected.
Unpivoting
Select the columns that should stay as they are, the identifier columns such as Program, then on the Transform tab choose Unpivot columns, then Unpivot other columns. Power Query turns every other column into two: Attribute (the old column name) and Value (the cell value). Rename them, for example Month and Target, and set their types.
There are three commands, and the difference matters when new columns arrive:
| Command | What it records in M | When a new month column appears next refresh |
|---|---|---|
| Unpivot other columns | The columns to keep (Program) | The new month is unpivoted automatically |
| Unpivot columns (selected) | Power Query usually records it as Unpivot other columns | Usually handled automatically |
| Unpivot only selected columns | The exact columns to unpivot (Sep, Oct, Nov) | The new month is left as a column |
Unpivot other columns is the robust choice for files that grow, because the M step names the columns to keep, not the ones to unpivot. Kwabena checked the formula bar after unpivoting the targets and saw the step name only Program:
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Promoted Headers", {"Program"}, "Attribute", "Value"),
#"Renamed Columns" = Table.RenameColumns(#"Unpivoted Other Columns", {{"Attribute", "Month"}, {"Value", "Target"}}),
#"Changed Type" = Table.TransformColumnTypes(#"Renamed Columns", {{"Target", Int64.Type}})Unpivoting also drops null values: if a program had no target for April, the unpivoted table simply has no April row for it. That is usually what you want, but it is worth knowing when counting rows.
Turning month names into dates
The unpivoted Month column held text: Sep, Oct, Nov. To relate the targets to the date table, Kwabena needed real dates. The academic year in the file was 2026 to 2027, so September to December belonged to 2026 and January to April to 2027. He added a conditional column for the year, merged it with the month text into a string such as "1 Sep 2026", and converted it with Change Type Using Locale to a date, the first of each month. Small transformations like this are often what turns a pivoted sheet into something a model can use.
Pivoting
Pivot column does the reverse: it turns the distinct values of one column into new columns. Select the column whose values become headers (for example Month), choose Pivot column, and choose the values column (Target) and an aggregate function under Advanced options: Count, Sum, Average, Minimum, Maximum, Median, or Don't aggregate. If each combination of the remaining columns has exactly one value, Don't aggregate works; if there are several, it produces errors, and you need an aggregate.
Pivoting is less common when preparing data for a model, but it has a classic use: when a source stores attribute and value pairs in rows. The advising system exported student details as StudentID, Field, Value, with rows such as Field = Advisor and Field = Cohort. Pivoting Field with Don't aggregate produced one row per student with Advisor and Cohort columns, which was the shape the student dimension needed.
Worked problem
Spotting when Don't aggregate fails
Kwabena pivots the advising export on Field using Don't aggregate. Most cells fill correctly, but some show Error. What has happened?
Show solution
- Don't aggregate requires one value for each StudentID and Field combination.
- An error means some combination has two or more rows, for example a student with two Advisor rows after a change of advisor.
- Group the source by StudentID and Field with a row count, and filter where the count is greater than 1, to find them.
- Decide with the data owner which value is right, such as the most recent, and remove the others before pivoting.
Answer: The source has duplicate field rows for some students. Resolve them first, or pivot with an aggregate such as Maximum if that gives the correct answer.
Transpose
Transpose swaps rows and columns completely: row 1 becomes column 1. It is a blunt tool, used when a whole table has been laid out sideways, such as a small summary where the metric names run down the first column and the campuses run across the top. Transpose loses the headers, so it is usually followed by Use first row as headers. For tables with headers on two levels, a common pattern is transpose, fill down or merge the header columns, transpose back and promote headers.
Grouping and aggregating rows
Group By, on the Home or Transform tab, summarizes rows. In the Basic mode you choose one grouping column and one aggregation; in Advanced mode, several grouping columns and several aggregations, such as Sum of Credits, Count Rows and Count Distinct Rows. The operations include Sum, Average, Median, Min, Max, Count Rows, Count Distinct Rows and All Rows, which keeps the grouped rows as a nested table for further work.
Grouping in Power Query reduces the rows loaded into the model, which can make a model smaller and faster. But it also removes detail permanently: a measure cannot drill below the grain you grouped to. Kwabena's rule was to load facts at the finest grain users might need, usually one row per registration, and let DAX measures aggregate. He used Group By in Power Query for three narrower purposes: profiling (counting values, as in lesson 3), building small summary tables for specific uses such as a monthly export to the province, and preparing data where the source grain was far finer than any report needed, such as card-reader swipes that he summarized to one row per student per day.
Converting semi-structured data to a table
Not every source is a table. Web APIs return JSON, and some systems export XML. Power Query reads these as nested structures: a record (like one row, a set of named fields) and a list (an ordered set of values). The objective *convert semi-structured data to a table* means turning these structures into rows and columns.
The student services booking system offered an API that returned appointments as JSON. Power Query opened the result as a list of records. Kwabena chose To Table on the List Tools tab, which produced a single column of records, then clicked the expand icon in the header to choose which fields became columns. One field, Attendees, held a list of its own; expanding it with Expand to New Rows gave one row per attendee.
let
Source = Json.Document(Web.Contents("https://bookings.example.org/api/appointments")),
AsTable = Table.FromList(Source, Splitter.SplitByNothing(), {"Record"}),
Expanded = Table.ExpandRecordColumn(AsTable, "Record", {"id", "date", "service", "attendees"}),
Attendees = Table.ExpandListColumn(Expanded, "attendees")
in
AttendeesA useful check after expanding: compare the row count before and after expanding a nested list. If each appointment has several attendees, expanding to new rows multiplies the rows, which is correct for an attendee table but wrong if you then sum something per appointment. Lesson 5's warning about merges applies here too.
Unpivoting messy spreadsheets
Real report-style sheets rarely unpivot cleanly on the first try. The program targets file had a Total column at the right and a Total row at the bottom, two header rows (a semester name above each group of months) and a note in the corner. Kwabena's approach was methodical. First, remove the junk: the note, the Total row (filter it out by the Program value Total) and the Total column. Totals must never be unpivoted, because the model can calculate them, and keeping them would double every sum. Second, deal with the two header rows: transpose, fill down the semester names, merge the semester and month into one header text, transpose back and promote headers. Third, unpivot other columns, keeping Program. Finally, split the combined header back into Semester and Month.
It sounds like many steps, and it is. But each step is visible in Applied steps and runs again automatically next year when finance sends the new targets in the same layout. The alternative, retyping the targets into a long table by hand, would have to be repeated every year and would invite typing mistakes.
Grouping for distinct counts
Group By offers Count Distinct Rows, which counts unique combinations of the remaining columns in each group. It is a handy profiling tool: grouping enrollment rows by Program with Count Distinct Rows of StudentID shows how many different students are in each program, which is different from the number of enrollment rows. For reports, though, distinct counts usually belong in DAX measures, because a distinct count calculated in Power Query cannot be re-aggregated: the number of distinct students in a school is not the sum of distinct students in its programs, because some students take courses in more than one.
XML and other semi-structured sources
XML behaves like JSON in Power Query. Opening an XML file or web response shows a table of elements, with nested tables for child elements; expand them level by level. Some files mix structures: a CSV where one column holds JSON text, for example. Power Query can parse such a column with Parse on the Transform tab, choosing JSON or XML, which turns the text into a record or list that can then be expanded. The provincial labor-market table, which Kwabena first expected to be a simple web table, arrived from an open-data API as JSON with a list of observations inside a record of metadata; drilling into the observations field, converting to a table and expanding gave him a long table of occupation, region, year and value.
Exam patterns for reshaping questions
Reshaping questions often show a small table before and after and ask which transformation produced the result. If column headers have become values in a column, the answer is unpivot. If values in a column have become headers, it is pivot. If the whole table has turned on its side, it is transpose. If many rows have become one per group with a total, it is Group By. When a question adds that new columns will appear in future files, the answer is Unpivot other columns.
Choosing the grain
Every reshaping decision is really a decision about grain: what one row of a table represents. The unpivoted targets table has one row per program per month. The enrollment fact has one row per student per course section per term. The card-reader summary has one row per student per day. Writing the grain down, in a sentence, before reshaping a table prevents most mistakes. If a merge or an expand produces rows that do not match the written grain, something has gone wrong. Kwabena put the grain in each query's description, so that the next analyst knew, for example, that the targets table was monthly and should never be summed with daily figures without care.
Grain also decides how tables relate. The monthly targets cannot relate to the daily date table on a day: they relate on the first day of each month, or on a month key. That is why Kwabena converted month names into first-of-month dates when he unpivoted. Getting the grain and the key right in Power Query makes the modeling much simpler.
Common mistakes
MistakeLoading a wide table with one column per month.
InsteadUnpivot so month is a column; the model keeps one shape as months are added.
MistakeUsing Unpivot only selected columns on a file that grows.
InsteadUse Unpivot other columns so new columns are unpivoted on refresh.
MistakeGrouping facts in Power Query and losing detail users need.
InsteadLoad facts at the finest useful grain and aggregate with measures.
MistakePivoting with Don't aggregate when duplicates exist.
InsteadFind and resolve duplicate pairs first, or choose an aggregate.
Summary and key terms
- Models prefer long, narrow tables; unpivot turns column headers into an Attribute and Value pair.
- Unpivot other columns names the columns to keep and handles new columns automatically.
- Pivot turns a column's values into columns, with an aggregate or Don't aggregate.
- Transpose swaps rows and columns and is usually followed by promoting headers.
- Group By summarizes rows; JSON and XML are converted with To Table and expand.
- Unpivot
- Turning several columns into attribute and value rows.
- Pivot
- Turning the values of a column into separate columns.
- Transpose
- Swapping the rows and columns of a whole table.
- Group By
- Summarizing rows into one row per group with aggregations.
- Record
- A Power Query structure of named fields, like a single row.
- List
- A Power Query structure holding an ordered set of values.
Practice problems
Work each problem on paper first, then reveal the answer to check.
A targets table has Program plus twelve month columns. What should you select before choosing Unpivot other columns?
Show answer
The Program column, the identifier to keep.
Why might Group By in Power Query be a poor choice for a sales fact table?
Show answer
It removes detail permanently, so reports cannot drill below the grouped grain.
How do you turn a JSON list of records into columns?
Show answer
Convert the list To Table, then expand the record column and choose fields.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.