Grouping or Summarizing Data

The Scenario

One of the most common request of an Excel pro is to group and summarize data. This pattern shows you how to create a compelling report from just a single source of data, which can be refreshed at any time with a single click.

The scenario uses a simple sales table which includes a listing of all products (t-shirts) sold, the date of sale, the sales channel and the total sales dollars for the product on that specific date.

Our Goals

We will start from a source table that has the following columns:

• Date
• ProductName
• ChannelName
• Amount

Our goal is to create a final report that summarizes that data and lists:

• The total amount per day for each channel,
• The total products sold in that channel,
• All the products sold, and
• The product with the highest sales.

We can break these into three separate sub-goals:

1. Create the column that sums all the amounts by date and channel,
2. Create a new column that represents a list of all the products separated by a commas, and
3. Create two extra columns that give us the name of the top selling product and its proportion of the total sales.

Let’s find out we can get from the Source Table to the Desired Result.

The Start

Once you open the workbook, head over to the Sales worksheet, where you’ll find a table. Select any cell inside that table, click the Power Query tab and choose From Table.

You’ll now be launched into the Power Query editor.

Goal 1: Grouping and Total Sum Column

Our first step starts by grouping the rows in our table using some criteria. Click the Group By button and set it up using the following criteria:

That should give us a table with a fewer amount of rows because all the data has been grouped by Date and Channel Name. We’ve even managed to create some new data as well, by creating a SUM of the Amount column, and a Count of Distinct Rows (yielding a count of distinct products by channel by day). We’ve also got a list of all products in the final step, which will make a bit more sense later…

A Best Practice: Define DataTypes

Whenever you pull a date into Power Query, we highly recommend that you specifically define the datatype for the date column. If you don’t, the data could be treated as type “any”, which means that it could land as either text or a value in your output instead of a date. It’s not hard to do at all, simply select the column header, go to the Transform tab, and change the Data Type to Date:

So we’ve now got a Total Sales and a Total Products by Channel, finishing our first goal.

Goal 2: Create a Comma Separated List of all Products Sold Each Day

Our next step is to create a formula for a new column that somehow:

• Takes all the products that were sold on that specific date and channel
• Creates a list of those products
• Transforms that List into a table
• Transposes that table into a table with multiple columns
• Merges all those columns delimited by a comma

This is the formula that does just that using Table.ToList Table.Transpose Table.FromList Table.Column and the Combiner function:

`Table.ToList(` Table.Transpose( Table.FromList( Table.Column([Products], "ProductName") ) ), Combiner.CombineTextByDelimiter(", ") )``

What this formula is doing

To better explain what this formula is doing, we are going to do each part of that formula as a new step. The formula defined above basically does all of these steps in a single step.

We start with the most inner function and that is Table.Column([Products], “ProductName”):

what this formula does is simply extract a column from a table and present it to us a List. So we end up having a list with the values from the ProductName column.

The next step is to transform that list into a Table so it can be easier for us to perform other type of operations. The function that transform a list into a table is called Table.FromList and we’ll use it now:
as you can see from the picture above, the new column has Table values for that whole column. We did that because we want to use another function to transpose those rows into columns. That function is Table.Transpose and that formula should read like this:

the result of that is basically a transposed table. So if we had N amount of rows and only 1 column now we’ll have 1 row with N amount of columns.

Our next step is to combine all the columns using a format similar to “Value1, Value2, Value3, …, ValueN”.

To do that, we use a Table.ToList that automatically does the operation of concatenating all of the strings into a single value. By Default, it uses a comma separator but in this case we want to go with a comma followed by a space (, ) and the second argument of Table.ToList allow us to do so by adding a Combiner function.

In our case, we’ll use this combiner function: Combiner.CombineTextByDelimiter(“, “) that does just exactly what we need.

And once you expand that column by clicking the arrows that go in opposite directions, and once we rename that column, this is the result of it:

We created the column that creates the list of all the products that were sold on that day, so we finished our 2nd goal. Let’s go to the next one.

Goal 3: Add columns for top sold Product and participation of it

Our next step is to extract the top product and also its amount on a row by row basis from the column Products which is this case is a table. We can do so by using a new custom column with the following Table.Max function:

once you create this new column, you’ll notice that it’ll populate with records which is a special type of data representation in Power Query and what we need is to extract the ProductName and Amount from that record.

We can do so by simply clicking on the opposite arrows icon that are next to the name of this new column. Click on that icon and you’ll notice a new selection window where you can select what columns you want to extract from that record. For now, just select the ProductName and the Amount columns.

Once we rename those columns this is how our table should look like:

We are almost there! we are missing the division of the Top Product amount over the Total Sales so we can get a % out of it. Let’s do so by adding a new custom column:

After spending some more time cleaning the data, this should be the result of our hard work:

You can click on Close & Load to save this table to your Workbook or inside your Data Model.

Note that you can refresh this at any time and it’ll work as desired.

Transform it into a Function

There are many ways to transform this into a function, but the basics of creating a function go into making a part of the whole code a variable.

Which one would you choose to make a variable? Let us know in the comments section below

This time, we’re choosing a simple variable. Since we need the Source step to be a table, let’s define that as our variable.

1. First we go to the View tab and click on Advanced Editor
2. Then we look at the M code in this Editor and replace the one that we’re trying to make a variable
3. We replace it with a variable and add the variable before the code as shown in the picture below

now we need to put this to the test. Let’s create a blank query and grab all the tables from our current Workbook using Excel.CurrentWorkbook():

next we add a custom column by using the name of the function that we just created which is the name of the Query SalesReport and the result should look like this:

Combine or Append Data from Files

This is a sample excerpt or description which will be added as meta to the post itself and should be displayed on the “description” area and RSS feeds.

Merge Tables

The Scenario If you’ve worked with Excel for any length of time, it’s almost certain that you’ve ended up with one table that has your…

NetWorkDays

The Scenario Power Query offers some date functions but none resembles Excel’s NETWORKDAYS to calculate the number of working days between two dates. In this…

Dynamic Calendar Table

The Scenario When you are facing a scenario where you need to create a Dynamic Calendar Table (or Date Dimension Table), we take in consideration…

VLOOKUP True in Power Query

About the Author of this Pattern The following VLOOKUP True pattern was created by a close friend of both Miguel Escobar and Ken Puls. His…

Responses

1. Hi,
Over the years I used this pattern in various variations again and again – and until now without any issues. Now I noticed that if in a text column there is a comma the inner part renders an error.

Table.FromList(
Table.Column([Products], “ProductName”)
)

=> DataFormat.Error: There were more columns in the result than expected.

Are there any possibilities to avoid the error apart from removing all the comma?

Thanks!

1. by default it tries to use the commas as separator, but you can define what splitter function to use as a second argument of the Table.FromList like this:
Table.FromList(
Table.Column([Products], “ProductName”),
Splitter.SplitByNothing()
)

However, there are probably better ways to tackle this depending on your case.

1. Miguel, that worked great:
I had about 25% lines with comma and now all the comma can remain and no error occurs. Thanks a lot!

2. Hi,
I do have two sheets in 1 excel workbook, One sheet contains ‘A’ data and the other sheet contains ‘B’ data, like the same way I do have 8 workbooks(each workbook has two sheets of A& B). All 8 workbooks data have to append in one workbook respectively of ‘A’ sheet data in ‘A’ sheet itself and ‘B’ sheet data in ‘B’ sheet itself accordingly

1. Hey!
I’m not sure I’m following as your scenario doesn’t appear to be related to the one from this article.

I’d highly recommend that you post your question with full details on a community forum such as the official power query forum:
https://social.technet.microsoft.com/Forums/en-US/home?forum=powerquery

Just be reading your post, it closely resembles a scenario that we have on our site for combining multiple files, but at the same time it’s probably a better idea if you provide all of the info on a forum so you can get the best advice with all the available info.

Best!

ARE YOU IN?

15K+ subscribers have already claimed their free eBook.