In this guide, we’ll see how to group data in Power Query in Excel, specifically using the feature called “Group By.”
This feature is great for reducing the size of your databases, since it lets you create “summaries” of the data that minimize the number of records needed to perform your analyses.
How many times have you found yourself with huge databases, perhaps with a single record per sale, when what you actually needed was the total number of sales? Or the number of orders for a specific period? Or even the average revenue per customer, calculated by summing their orders? In these cases, you don’t need to see every single row, since they’re not relevant to your analysis. What you’re looking for is a quick way to reduce the total number of rows and extract only the parts of this database that can help with your analysis, all of this can be done directly using the Power Query interface, thanks to the “Group By” feature.
Here’s an example of how to use “Group By” to create a top 10 list in Excel.
We’ll use a sales database as an example, assuming we’re selling Lego sets. The database has the following columns:

- Product: Product ID
- Customer: Customer ID
- Price: Price per set
- Date: Sale Date
- #_SET: Number of sets sold in the order
- Total: Revenue calculated as price * sets
- LEGO_SET: Name of the LEGO set
- Pieces: number of pieces per set
- Region: customer's region
- AGE: customer's age
How to Group Data in Power Query in Excel: A Simple Case
Let’s look at a typical scenario that requires grouping data in Excel, for example, we have a sales database and want to group the data to reduce the number of records, as the file risks becoming enormous and unmanageable by our standards.
The question we’re answering: “What are the best-selling products, ranked from highest to lowest sales?”
Let’s take a look at our initial sales database. Which columns do we need? In this case, there are only two, since we’ll get our result by using the product and sales revenue.
In Excel, as you know, there are often several ways to achieve the same result. In this case, we have at least three options:
- Using PivotTables
- Using Formulas
- Using Power Query
In this guide, I won’t cover PivotTables, but you can find a dedicated guide to creating PivotTables in Excel here.
Let’s look at an intuitive solution using formulas, which leverages the GROUPBY function:

=GROUPBY(TBL_PRODUCT_SALES[PRODUCT],
TBL_PRODUCT_SALES[TOTAL_REVENUE],
SUM,
,0,-2)
This function allows us to perform the following operations all at once:
- Select the PRODUCT column from the table named TBL_PRODUCT_SALES, which will populate our rows with unique values
- Select the TOTAL_REVENUE column from the TBL_PRODUCT_SALES table, which we’ll use for our calculations
- In fact, we want the SUM of the data, without headers or totals, sorted by total (-2)
If you wanted to recreate the same process step by step, we could do it like this:
- Let’s retrieve the individual values by product ID using UNIQUE
- Let’s sum the total for each of them using SUMIFS
- We sort our matrix, using SORT, starting with revenue

In summary, something like this:
=LET(products,TBL_COMBINED[PRODUCT],
unique_products,UNIQUE(products),
revenue,TBL_COMBINED[TOTAL],
final,SORT(
HSTACK(unique_products,
SUMIFS(revenue,products,unique_products)),
2,-1),
final)
Let’s break it down in detail:
- LET: This is a function that allows you to assign names to intermediate calculations. It is useful for simplifying complex formulas, making them more readable and potentially more efficient.
- products,TBL_COMBINED[PRODUCT]: This part assigns the name “products” to the data in the “PRODUCT” column of a table called “TBL_COMBINED.” It is the first intermediate calculation
- unique_products,UNIQUE(products): Here, “unique_products” is assigned to the list of unique values in the “PRODUCT” column. The function UNIQUE removes duplicates.
- turnover,TBL_COMBINED[TOTAL]: This part assigns the name "turnover" to the data in the "TOTAL" column of the same "TBL_COMBINED" table.
- final,SORT(...): Here, the name “final” is defined. The associated calculation uses the function SORT to sort the data resulting from a function HSTACK.
- HSTACK(unique_products, SUMIFS(revenue, products, unique_products)): The function HSTACK horizontally combines two data sets. Here, it combines “unique_products” with the result of the function SUMIFS, which calculates the total “revenue” for each unique “product.”
- 2,-1: These are the parameters of the function SORT. “2” indicates that the data is sorted based on the second column of the range (in this case, the sums calculated by SUMIFS), while “-1” indicates that the sort is in descending order.
- final: After defining all intermediate calculations, the LET function returns the “final” value, which is the result of the sort.
As we mentioned, there are several ways to achieve the same result. The formula above might seem intuitive to some, but you’ve probably gotten a headache trying to follow the various steps, that happens to me if I’m not the one creating the formula myself, since I have to get into someone else’s line of reasoning, and it doesn’t always align perfectly with how I would have approached it.
Let’s see how to achieve the same result with Power Query, greatly simplifying the process.

First of all, we need to import the values from our table into Power Query. In this case, since the table is in the same file, we can use the command Data > Get Data From > From Other Sources > From Table/Range. If the data were located elsewhere, the process would be the same but the connector would change: for example, you might need to select Data > Get Data > From File > From Text/CSV or similar.

At this point, we see that our source table is named TBL_COMBINED. We don’t want to modify it, so we click on the query > right-click > Reference. The Reference option will create a new query that corresponds to the last step of the source query, so it will reflect any changes we make to the data in the query named TBL_COMBINED. This is the best way to retrieve data, as it reduces the number of steps, if we had selected “Duplicate,” Power Query would have created a new query identical to the original, and this could significantly increase the computational load if we were working with large databases.

At this point, let’s rename the new query as we see fit, in this case, the new table will be called TBL_PRODUCT_SALES. Since we now have a new environment for working with our data, we can click Home > Group By. A context menu will open where we can define how we want to create this grouping.

Let's talk about the basic options. You can select a column, in this case, PRODUCT, which will serve as our key for summarizing the data. Next, you can define three different values:
- New Column Name: the header for the new column
- Operation: the operation you need
- Column: Which column Power Query should use for the calculations
We saw earlier the Excel formula that included the part called "SUMIFS(revenue,products,unique_products)." Here, the process is similar because we’re telling Power Query that:
- Column: We want the column to be PRODUCT, since the analysis relates to these values and we want to ensure there are no duplicates
- New column name: We’ll call it TOTAL_REVENUE since we’re talking about the sum of revenue totals by product
- Operation: Since we’re dealing with sums, select Sum
- Column: Since the revenue values are in the TOTAL column, we’ll select it
The reasoning is quite logical and, I believe, much simpler than constructing the formula we saw earlier.

Power Query will return all products along with their total revenue. It does this at a speed that’s incomparable to formulas, plus it has the advantage of being fully scalable, if the source data changes, we’d simply need to update the query to get the new calculations without risking overloading our PC.

At this point, I’ll round the final data, just as a precaution, simply click on the TOTAL_REVENUE column, then go to Transform > Rounding > Round… and choose the number of decimal places you want. It’s not an essential step, but it can help with the final analysis by reducing any potential inaccuracies.
Note: As my friend Enrico de Crescenzo rightly pointed out, this procedure works fine if we need approximate data, but if the figures need to match the initial data down to the cent, it’s best to avoid it and use the unrounded totals directly!

At this point, we can sort the total revenue by clicking on the header and selecting the “Sort Descending” option. We’ll then have all our values sorted from highest to lowest sales, just as we wanted.

All that’s left is to click Close and Upload > Close and Upload to… and choose how we want to upload this new table to our Excel workbook!

If we load it as a table, we’ll end up with a much smaller table containing only 17 products and their sales figures, avoiding the need to load all the data into our Excel workbook and significantly reducing the file size!
How Power Query Code Works When We Group Data
As you know, Power Query generates M code to summarize all these steps, and you can view it by going to Home > Advanced Editor. Let’s take a closer look, using the simple example from earlier:
let
Source = TBL_COMBINED,
#"Grouped Rows" = Table.Group(Source, {"PRODUCT"}, {{"TOTAL_REVENUE", each List.Sum([TOTAL]), type nullable number}}),
Rounded Off = Table.TransformColumns(#"Grouped Rows",{{"TOTAL_REVENUE", each Number.Round(_, 2), type number}}),
#"Sorted Rows" = Table.Sort(Rounded Off,{{"TOTAL_REVENUE", Order.Descending}})
in
#"Sorted Rows"
I’ll also provide a brief explanation for each step, in case you’d like to learn more about what happens when we click the individual Power Query buttons:
- Defining the data source: Source = TBL_COMBINED: Here, we are defining a Source variable that references the TBL_COMBINED table. This will be the starting table for subsequent transformations.
- Row grouping: #"Group Rows" = Table.Group(...): In this step, the query groups the rows of the Source table based on the value in the "PRODUCT" column. For each unique "PRODUCT" group, it calculates the sum of the values in the "TOTAL" column. The result is a new table with two columns: “PRODUCT” and “TOTAL_REVENUE” (the latter containing the sum of “TOTAL” for each product).
- Rounding values: Rounded = Table.TransformColumns(...): This step transforms the "TOTAL_REVENUE" column of the table resulting from the grouping. It uses the function Number.Round(_, 2) to round each value in the "TOTAL_INVOICED" column to two decimal places. The column retains its number data type.
- Sorting the Rows: #"Sorted Rows" = Table.Sort(...): Finally, the table is sorted by the "TOTAL_REVENUE" column in descending order. This means that the products with the highest total revenue will be listed first.
- Final result: in #"Sorted Rows": The final result of this query is the sorted table, identified as #"Sorted Rows".
EXCEL TRAINING
Want to bring these skills to your team?
I design Excel training paths based on your goals, the participants' level and the cases you actually face at work.

Marco Filocamo · Microsoft Excel MVP
Do you have a specific file or process to improve? Explore Excel consulting →
How to Group Data in Power Query in Excel: A Complex Case
Now let’s see how to group data in Power Query using a complex example. This time, we don’t need to find the total revenue per product; instead , the question is: “For each quarter, what are the total revenue, total number of sets sold, total number of orders, average revenue per order, and median revenue per order for each customer?”
This seems like a lot of information to condense into a single dimension, and doing so with formulas could be quite tedious, so let’s look directly at how to handle this in Power Query.

Once again, let’s start by referencing the TBL_COMBINED table and naming it TBL_QUARTERLY_CUSTOMER_SALES (since “quarter” refers to a quarter). Note that the “quarter” column doesn’t exist in our initial table, so we’ll need to add it.

Power Query has many options to help us extract values from the calendar, in this case, we simply need to go to the DATE column, then click Add Column > Date > Quarter > Quarter of the Year.

As you can see, Power Query will create a new column called “Quarter,” which will have a numeric value from 1 to 4 depending on the reference month of each date.

Now we can go back to Home > Group By and select the values we’re interested in. In the Advanced section, we can significantly expand our options, since:
- We can select multiple columns to group by. There is a hierarchical order here, so the one at the top takes precedence over the ones below it
- We can select multiple columns in the calculations section by clicking on “Add Aggregation”
As you can see, we select CUSTOMER and Quarter as the basis, since we want this data to be summarized by customer and by quarter. Next, we select the columns we’re interested in by giving them a custom name, defining an operation, and referencing the column we want. The only case where there isn’t a column is “Count Rows,” since this operation will simply count the number of records corresponding to the selected Customer + Quarter combination.

At this point, we’ve consolidated all the information we need. As you can see, we have CUSTOMER, then Quarter, and then all the columns we’re interested in.

If we wanted to sort the data correctly, we’d need to take an additional step since the IDs are text. The order in Excel would therefore be ID1, ID10, ID11, and so on. In this case, you could add a column using “Add Column” with “Column from Examples” and create it from “CUSTOMER,” extracting the various numbers and then sorting the entire range first by this new column (which you’ll later delete) and then by individual quarter.
This way, you’ll have an order like ID1 | 1 / ID1 | 2 / ID1 | 3 / ID1 | 4 / ID2 | 1 and so on, instead of a strange order dictated solely by the ID.

At this point, we have our summary table with all the data we need, and all that’s left is to import it back into Excel.

The final version is the one you see here in the image! In one fell swoop, we can consolidate numerous operations, exponentially speeding up the creation of our files.
How Power Query code works when we group data in complex ways
Let’s now see what happens on the code side when we perform numerous operations, as in this complex Power Query scenario:
let
Source = TBL_COMBINED,
#"Quarter Entered" = Table.AddColumn(Source, "Quarter", each Date.QuarterOfYear([DATE]), Int64.Type),
#"Grouped Rows" = Table.Group(#"Inserted Quarter", {"CUSTOMER", "Quarter"}, {{"TOTAL_REVENUE", each List.Sum([TOTAL]), type nullable number}, {"TOTAL_SETS", each List.Sum([#"#SET"]), type nullable number}, {"AVERAGE_ORDER", each List.Average([TOTAL]), type nullable number}, {"MEDIAN_ORDER", each List.Median([TOTAL]), type nullable number}, {"NUMBER_OF_ORDERS", each Table.RowCount(), Int64.Type}}),
#"Text entered after the delimiter" = Table.AddColumn(#"Grouped Rows", "Text After Delimiter", each Text.AfterDelimiter([CUSTOMER], "D"), type text),
#"Type Modified" = Table.TransformColumnTypes(#"Inserted Text After Delimiter",{{"Text After Delimiter", Int64.Type}}),
#"Sorted rows" = Table.Sort(#"Changed Type",{{"Text After Delimiter", Order.Ascending}, {"Quarter", Order.Ascending}}),
#"Columns removed" = Table.RemoveColumns(#"Sorted Rows",{"Text After Delimiter"})
to
#"Columns removed"
More specifically, here are the individual steps:
- Defining the Data Source: Source = TBL_COMBINED: The query begins by defining Source as a reference to the TBL_COMBINED table. This table will serve as the basis for subsequent transformations.
- Adding the Quarter: #"Added Quarter" = Table.AddColumn(...): Here, a new column named "Quarter" is added to the Source table. This column is calculated using the function Date.QuarterOfYear([DATE]), which determines the quarter of the year for each date in the "DATE" column.
- Grouping Rows: #"Grouped Rows" = Table.Group(...): This step groups the rows in the table based on the “CUSTOMER” and “Quarter” columns. For each unique combination of customer and quarter, it calculates various aggregates: the total sum of "TOTAL" and "#_SET," the mean and median of "TOTAL," and the number of orders.
- Insert Text After Delimiter: #"Text Inserted After Delimiter" = Table.AddColumn(...): Adds a new column that extracts the text following the character "D" in the customer name (using Text.AfterDelimiter([CUSTOMER], "D")).
- Data Type Modification: #"Data Type Modified" = Table.TransformColumnTypes(...): Changes the data type of the new "Text after the Delimiter" column to Int64.Type, indicating that this text is interpreted as a number.
- Sorting Rows: #"Sorted rows" = Table.Sort(...): Sorts the table first by the new "Text after delimiter" column in ascending order, and then by quarter, also in ascending order.
- Removing Columns: #"Removed Columns" = Table.RemoveColumns(...): Removes the "Text after the delimiter" column from the sorted table.
- Final Result: in #"Removed Columns": The final result of the query is the table with the columns removed.
You don’t need to know all these commands, but it might be helpful if you want to learn more about working with M in Power Query!
Conclusions
As you’ve seen, grouping data with Power Query in Excel has numerous advantages. First of all, it significantly reduces file size. Second, it allows you to easily create scalable structures. Finally, it’s easy to verify, since the entire process is tracked in the queries!
I strongly recommend using this feature when you’re working with large databases, as it will greatly help you avoid errors and quickly arrive at the results of your analyses.
