Sub topic 13
Summarizing data with Group By
This chapter assumes you can open the Power Query Editor, read the Applied Steps pane, and set data types on columns. It also assumes you have already cleaned the source table, because Group By summarizes whatever it receives. If a region appears as "East" and "East " (with a trailing space), the result has two rows.
What Group By does
Group By collapses many rows into one row per unique combination of values in the columns you choose. For each group it computes one or more aggregates, such as a sum, a count, or an average. The result is a new, smaller table. The detail rows are gone from that query.
This is similar to a PivotTable, but the output is an ordinary table that later steps can use. You can append it, merge it with other queries, or load it to a worksheet. It refreshes with the rest of the query.
| Need | Better choice |
|---|---|
| A summary table that feeds another query or a chart | Group By |
| Interactive slicing of detail data | PivotTable |
| A per-row calculation that keeps all detail rows | Custom column |
Basic grouping in the editor
- Select the query, then choose Transform > Group By.
- In the dialog, keep Basic selected.
- Choose the column to group by, for example Region.
- Enter a name for the new column, choose an operation, and choose the column to aggregate.
- Select OK.
The operations in the Basic dialog are Sum, Average, Median, Min, Max, Count Rows, and Count Distinct Rows. Count Rows does not need a source column, because it counts rows in each group.
Power Query records this as one step. The following query groups the cleaned sales table by Region and sums Amount.
let
Source = Excel.CurrentWorkbook(){[Name="SalesClean"]}[Content],
Grouped = Table.Group(Source, {"Region"}, {{"TotalAmount", each List.Sum([Amount]), type number}})
in
GroupedTable.Group takes three arguments:
- The table to summarize.
- A list of the key columns, written in braces.
- A list of aggregations. Each aggregation is a list of three items: the new column name, a function, and the type of the result.
In each List.Sum([Amount]), the each keyword creates a function that runs once per group. Inside it, [Amount] is not a single value. It is the entire Amount column for the rows in that group, as a list. That is why you use a list function such as List.Sum here.
Grouping by more than one column
Choose Advanced in the dialog to add more grouping columns and more aggregations. Group by Region and Product to get one row per combination.
let
Source = Excel.CurrentWorkbook(){[Name="SalesClean"]}[Content],
Grouped = Table.Group(
Source,
{"Region", "Product"},
{
{"TotalAmount", each List.Sum([Amount]), type number},
{"Orders", each Table.RowCount(_), Int64.Type},
{"AvgAmount", each List.Average([Amount]), type number}
}
)
in
GroupedHere _ stands for the whole sub-table for the group. Table.RowCount(_) counts its rows. This is what the Count Rows operation generates.
How the groups are formed
The diagram shows what happens inside the step.
Rows in the result appear in the order in which each key first appears in the source. They are not sorted. Add a Sort Rows step afterward if you need a particular order.
Other aggregations
The Basic list is short. In the M code you can use any function that accepts a list or a table.
List.MinandList.Maxfor the smallest and largest value.List.Countfor the number of items, including nulls.List.NonNullCountfor the number of items that are not null.List.Distinctcombined withList.Countfor a distinct count of one column.List.StdDevfor the standard deviation.Text.Combineto join text values in each group, for exampleeach Text.Combine([Product], ", ").
You can also keep the detail rows inside each group. The All Rows operation in the dialog stores each group's sub-table in a cell. Use the expand button on the column header to bring selected columns back. This is useful when you need to do more work per group, such as taking the top row of each.
Edge cases
Nulls in the key column
Rows with a null key are grouped together into their own group. They are not dropped. If you do not want that group, filter nulls out of the key column before grouping, or fill them with a label such as "Unknown" using Replace Values.
Nulls and errors in the value column
List.Sum, List.Average, List.Min, and List.Max ignore nulls. List.Average divides by the number of non-null values, not the number of rows. An average of 10, 20, and null is 15, not 10.
An error in a value cell is different. If any cell in the aggregated column holds an error, the aggregate for that group becomes an error. Find and fix those cells first. See the chapter on finding and handling errors. A text value that looks like a number will also cause trouble, which leads to the next point.
Data types decide the result
Set the type of the value column before you group. If Amount is still text, Sum fails. If a key column holds both text and numbers in different rows, you may get groups that look identical on screen but differ in type. Convert the key column to a single type first.
Case and spacing in keys
Group By compares keys exactly. "east", "East", and "East " are three groups. Use Trim, Clean, and a case transformation before you group.
Column names and refreshes
M refers to columns by name. If someone renames Amount in the source, the Group By step fails on the next refresh with a message that the column was not found. Keep source headers stable, or add a rename step early that maps the new name back.
Query folding
When the source is a database, Group By can often be translated into a SQL GROUP BY and run on the server. That is faster, because less data travels to Excel. Operations with no SQL equivalent, such as Text.Combine, may stop folding. For Excel tables and CSV files, folding does not apply.
Practical patterns
Group first, then merge
When you need a lookup that returns one row per key, group the lookup table first. Merging against a table with duplicate keys multiplies rows in the result. Grouping the lookup table to one row per key avoids that.
Count duplicates
Group by the key, add a Count Rows aggregation, and filter for counts above 1. The result lists every key that is duplicated and how many times.
Group a date by month
Add a column that holds only the month before grouping. Use Add Column > Date > Month > Start of Month, then group by that column. If you group by the raw date, each day is its own group.
let
Source = Excel.CurrentWorkbook(){[Name="SalesClean"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"Date", type date}, {"Amount", type number}}),
MonthStart = Table.AddColumn(Typed, "Month", each Date.StartOfMonth([Date]), type date),
Grouped = Table.Group(MonthStart, {"Month"}, {{"TotalAmount", each List.Sum([Amount]), type number}}),
Sorted = Table.Sort(Grouped, {{"Month", Order.Ascending}})
in
SortedEditing an existing Group By step
Select the gear icon beside the step in Applied Steps to reopen the dialog. You can add aggregations or change the key columns. If you edit the M code by hand, keep each aggregation as a three-item list. A missing brace is the most common syntax error.
Exercise
A table has columns Region, Product, and Amount. You group by Region and sum Amount, but the result shows both "North" and "North " as separate rows. What went wrong, and what should you do?
Show answer
Group By compares keys exactly, so the trailing space makes "North " a different key from "North". Add a step before Group By that trims (and cleans) the Region column, for example with Transform > Format > Trim, then group again. The two rows will merge into one.
Exercise
Write a Table.Group call that groups the SalesClean table by Region and returns two columns: the number of rows (Orders) and the largest Amount (MaxAmount).
Show answer
Table.Group(Source, {"Region"}, {{"Orders", each Table.RowCount(_), Int64.Type}, {"MaxAmount", each List.Max([Amount]), type number}})
Exercise
The values for one group are 10, 20, and null. What do List.Sum and List.Average return, and why does the average matter when you compare it with a spreadsheet calculation over all rows?
Show answer
List.Sum returns 30 and List.Average returns 15, because both ignore null. The average divides by two non-null values, not three rows. A formula that treats the blank as zero would give 10, so the two results differ.