Skip to content

Creating a Generalisable function

The steps on Generalised unpivoting work for any number of heading levels, but they still have to be clicked through for each report. Where several reports share the same kind of layout with different numbers of levels, it is quicker to write the steps once as a function. Each report then needs a single step that calls the function with a description of its layout.

The function takes four inputs:

  • Source, the summary table as it is loaded
  • RowFields, a list of names for the row heading levels, from outermost to innermost
  • ColumnFields, a list of names for the column heading levels, in the same order
  • ValueField, the name to give the column of values

The lengths of the two lists give N and M, so the function never needs them as numbers.

Create each input as a query of its own. On the Home tab, choose New Source, then Other Sources, then Blank Query, and type the value into the formula bar.

RowFields lists the row headings:

The RowFields query, whose formula is a list of Country, State/Region and City

ColumnFields lists the column headings:

The ColumnFields query, whose formula is a list of Color, Parent Category and Category

ValueField holds the name of the value column, which here is Revenue:

The ValueField query, holding the text Revenue

Load the summary table as its own query. Its row headings sit in the first columns and its column headings in the first rows, as on the previous page, but here the range has no empty row at the top.

The source table in the editor, with Color, Parent Category and City \ Category labels in Column3, the colour, parent category and category headings across rows 1 to 3, and countries, states and cities down the first three columns from row 4

Create another blank query, open the Advanced Editor, replace its contents with the code below and name the query, for example fnUnpivotTable:

(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"

The steps are the same as the ones clicked through on the previous page. What changes is that each column list is worked out from the inputs instead of being typed in. The pattern that does this is List.FirstN(Table.ColumnNames(table), count): Table.ColumnNames lists a table’s columns in order, and List.FirstN keeps the first count of them.

#"Filled Down" = Table.FillDown(Source, List.FirstN(Table.ColumnNames(Source), List.Count(RowFields) - 1)),

Table.FillDown takes a table and the names of the columns to fill. List.Count(RowFields) is N, so the step fills the first N-1 columns, which are every row heading except the innermost.

#"Merged Columns" = Table.CombineColumns(#"Filled Down", List.FirstN(Table.ColumnNames(#"Filled Down"), List.Count(RowFields)), Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Merged"),

This step takes all N row heading columns, including the innermost one, and joins them with a colon into one column called Merged.

#"Filled Down1" = Table.FillDown(#"Transposed Table",List.FirstN(Table.ColumnNames(#"Transposed Table"), List.Count(ColumnFields)-1)),

After transposing, the column headings run down the first M columns. This step counts ColumnFields instead of RowFields, and fills the first M-1 of them.

#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Promoted Headers",List.FirstN(Table.ColumnNames(#"Promoted Headers"), List.Count(ColumnFields)) , "Attribute", ValueField),

Table.UnpivotOtherColumns keeps the columns it is given and unpivots everything else. Here it keeps all M column heading columns. Its last argument names the new value column, so passing ValueField gives that column its final name, Revenue, straight away.

#"Split Column by Delimiter" = Table.SplitColumn(#"Unpivoted Other Columns", "Attribute", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), RowFields),

The last argument of Table.SplitColumn can be a list of names for the new columns, which also sets how many columns to split into. RowFields is exactly that list, so the merged label splits into Country, State/Region and City with no renaming needed.

#"Renamed Columns" = Table.RenameColumns(#"Split Column by Delimiter", List.Zip({List.FirstN(Table.ColumnNames(#"Split Column by Delimiter"), List.Count(ColumnFields)), ColumnFields})),

The row heading columns and the value column already have their final names, so only the first M columns still carry the merged headers, such as ::Color. Table.RenameColumns expects a list of pairs, each an old name and a new name, and List.Zip builds that list from two lists by pairing their items in order.

Here the first list is the current names of the first M columns and the second is ColumnFields, so ::Color becomes Color, and so on.

#"Changed Type" = Table.TransformColumnTypes(#"Renamed Columns",{{ValueField, type number}})

The last step sets the value column, found by the name in ValueField, to type number, which Power Query shows as Decimal Number.

Create a query called Results that calls the function with the source table and the three layout queries:

The Results query, whose formula is fnUnpivotTable(#“Source Data”, RowFields, ColumnFields, ValueField), returning Parent Category, Category, Country and State/Region columns

The query and function names in this capture differ from the earlier ones, because they were renamed along the way. The call should use whatever names the source query and the function have in your own workbook.

A second report with a different layout needs only its own RowFields, ColumnFields and ValueField queries, or the lists written straight into the call. Nothing in the function refers to a particular column name or a particular number of levels, so it works for any table where:

  • the row headings fill the first N columns
  • the column headings fill the first M rows
  • no heading contains a colon, because the colon is used to merge and split the labels