Skip to content

The Challenge! - combining revenue files

This exercise brings the earlier pages together. Four years of revenue data sit in one folder, in two different layouts:

  • 2015.xlsx, 2016.xlsx and 2017.xlsx each have a sheet per month, named Jan to Dec. Each sheet is a summary table, with customer category and city down the side, colour, supplier category and supplier name across the top, and grand totals on the last row and column.
  • 2018.csv holds the same facts as a list of records, one field per line. Each record is a run of seven lines, from Date to Revenue, and the next record starts straight after.

The goal is one table with a row per revenue figure and the columns Date, Color, Supplier Category, Supplier Name, Customer Category, City and Revenue.

The four source files, with arrows showing a monthly summary sheet from the Excel workbooks and the stacked attribute and value lines of the 2018 CSV both feeding into one flat table with Date, Color, Supplier Category, Supplier Name, Customer Category, City and Revenue columns

The work splits into three parts:

  1. Combine the 36 monthly sheets from the three workbooks.
  2. Reshape the CSV.
  3. Append the two results.
  1. On the Data tab, choose Get Data, then From File, then From Folder, select the folder and choose Transform Data.

The folder’s files in the editor, listing 2015.xlsx, 2016.xlsx, 2017.xlsx and 2018.csv with their content, extension and dates

  1. Filter the Name column to remove 2018.csv, because it needs different handling.

The file list filtered to the three xlsx files

  1. Rename the query Revenues.

Click the Combine Files button in the header of the Content column. In the Combine Files dialog, right-click the top node, Sample File Parameter1, and choose Edit, instead of selecting a single sheet.

The Combine Files dialog, with the Sample File Parameter1 node above the twelve month sheets Apr to Sep

Selecting the file node rather than one sheet means each workbook returns its list of sheets, so all twelve months come through instead of one. Power Query also creates the helper queries that every folder combine needs, which apply the same steps to each file in turn.

The Queries pane, with a Transform File from Revenues group holding the sample file, its parameter, the Transform Sample File from Revenues query and the Transform File from Revenues function, and the Revenues query under Other Queries

Back in the Revenues query, keep only the first three columns, which hold the file name, the sheet name and the sheet’s data.

The Revenues query with Source.Name, Name and Data columns, listing 2015.xlsx against the sheets Jan to Sep

Then tidy the first two columns:

  • Remove the .xlsx extension from Source.Name, for example with Extract, then Text Before Delimiter on the Transform tab, and rename the column Year.
  • Rename Name to Month.

The query with a whole-number Year column reading 2015, a Month column reading Jan to Sep, and the Data column

Each monthly sheet has an empty first row, a grand total column and a grand total row, and all three have to go before the sheet can be unpivoted. A small function does this for any table passed to it. Create a blank query called fnCleanSummarizedTable, open the Advanced Editor and enter the function. The first line of the block below is the query’s name, not part of the code:

fnCleanSummarizedTable
(inputTable) =>
let
SkipFirstRow = Table.Skip(inputTable, 1),
NoGrandTotalColumn = Table.RemoveColumns(SkipFirstRow, { List.Last(Table.ColumnNames(SkipFirstRow)) } ),
Result = Table.RemoveLastN(NoGrandTotalColumn, 1)
in
Result

The function does three things, in order:

  1. Table.Skip drops the first row.
  2. Table.RemoveColumns drops whichever column is last, which is the grand total.
  3. Table.RemoveLastN drops the last row, which is the grand total row.

In the Revenues query, add a step that applies the function to every sheet:

= Table.AddColumn(#"Renamed Columns", "fnCleanSummarizedTable", each fnCleanSummarizedTable([Data]))

The Revenues query with a new fnCleanSummarizedTable column holding a cleaned table beside each Data table

Rename the new column Summarized Table, and remove the Data column.

Unpivot each sheet with the generalised function

Section titled “Unpivot each sheet with the generalised function”

The cleaned sheets have two levels of row headings and three levels of column headings, which is the case the generalisable function handles. Create a blank query for it and paste in the code below. This version wraps the function in an outer let, which makes no difference to how it runs, and again the first line is the query’s name:

fnUnpivotSummarizedTable
let
Source = (Source, RowFields, ColumnFields, ValueField)=>
let
#"Filled Down" = Table.FillDown(Source, List.FirstN(Table.ColumnNames(Source), List.Count(RowFields) - 1)),
#"Merged Columns" = Table.CombineColumns(#"Filled Down", List.FirstN(Table.ColumnNames(#"Filled Down"), List.Count(RowFields)), Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Merged"),
#"Transposed Table" = Table.Transpose(#"Merged Columns"),
#"Filled Down1" = Table.FillDown(#"Transposed Table",List.FirstN(Table.ColumnNames(#"Transposed Table"), List.Count(ColumnFields)-1)),
#"Promoted Headers" = Table.PromoteHeaders(#"Filled Down1", [PromoteAllScalars=true]),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Promoted Headers",List.FirstN(Table.ColumnNames(#"Promoted Headers"), List.Count(ColumnFields)) , "Attribute", ValueField),
#"Split Column by Delimiter" = Table.SplitColumn(#"Unpivoted Other Columns", "Attribute", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), RowFields),
#"Renamed Columns" = Table.RenameColumns(#"Split Column by Delimiter", List.Zip({List.FirstN(Table.ColumnNames(#"Split Column by Delimiter"), List.Count(ColumnFields)), ColumnFields})),
#"Changed Type" = Table.TransformColumnTypes(#"Renamed Columns",{{ValueField, type number}})
in
#"Changed Type"
in
Source

In Revenues, add a step that calls it on every cleaned sheet, with the row and column headings written straight into the call:

= Table.AddColumn(#"Removed Columns", "Unpivoted", each fnUnpivotSummarizedTable([Summarized Table], {"Customer Category", "City"}, {"Color", "Supplier Category", "Supplier Name"}, "Revenue"))

The Revenues query with Year, Month, Summarized Table and a new Unpivoted column, one row for each month of 2015

Remove the Summarized Table column. Then click the expand button on Unpivoted, clear Use original column name as prefix, and click OK. Each month’s rows now appear under the year and month they came from.

The expanded rows, with Year 2015 and Month Jan beside Color, Supplier Category, Supplier Name and Customer Category values

That completes the workbooks. The CSV still needs reshaping before the two can be joined.

In the editor, choose New Source, then File, then Text/CSV, select 2018.csv and name the query 2018 Revenues.

The CSV in the editor as two columns, with Attribute and Value on the first row, then Date, Color, Supplier Category, Supplier Name, Customer Category, City and Revenue repeating down Column1 beside their values

Choose Use First Row as Headers, so the columns become Attribute and Value.

On the Add Column tab, choose Index Column, then From 0.

The query with a new Index column counting the lines from 0

Every record starts with a Date line. On the Add Column tab, choose Conditional Column and set it up as follows:

  • Name the new column Row ID.
  • If Attribute equals Date, output the value of the Index column.
  • Otherwise, output null.

The Add Conditional Column dialog creating Row ID, which returns the Index column where Attribute equals Date and null otherwise

Each Date line now carries its own line number, and the other lines of the record are empty.

The Row ID column, holding 0 on the first Date line and 7 on the next, with null on the lines between

Select Row ID and choose Fill, then Down on the Transform tab. All seven lines of a record now share the same ID, which is what lets them be gathered into one row. Then remove the Index column.

The Row ID column after Fill Down, reading 7 on every line of the second record and 14 on every line of the third

Select Attribute and choose Pivot Column on the Transform tab. Set Values Column to Value, open Advanced options and choose Don’t Aggregate, because each record has exactly one value for each attribute.

The Pivot Column dialog, using the names in Attribute for the new columns, with Value as the values column and Don’t Aggregate selected

Each record is now one row, identified by its Row ID, with a column for each attribute.

The pivoted table, with Row ID values 35, 42, 49 and so on beside Date 2018 Jan, Color Black, Supplier Category Clothing Supplier and Supplier Name

The Row ID has done its job, so remove it.

The finished 2018 Revenues query, starting with the Date, Color, Supplier Category, Supplier Name and Customer Category columns

The workbook rows have the year and month in separate columns, while the CSV has one Date column holding values such as 2018 Jan. In the Revenues query, select Year and Month, choose Merge Columns on the Transform tab, set the separator to Space and name the new column Date.

The Merge Columns dialog with Space as the separator and Date as the new column name

Both queries now have the same column names, which is what Append matches on.

  1. In the Revenues query, choose Append Queries on the Home tab and append 2018 Revenues.
  2. Set the type of Date to Date, which turns 2015 Jan into the first day of that month, and the type of Revenue to Currency.
  3. Choose Close & Load.

The loaded table, starting with Date 01/01/2015, Color Black, Supplier Category Clothing Supplier and Customer Category Computer Store, with a City and a Revenue on each row

All four years now sit in one table with one layout. Because every step works from the folder and from the structure of each file rather than from fixed names, dropping a 2019.xlsx into the folder adds its twelve months on the next refresh.