Search code examples
mergepowerquerym

Is there a way to expand dynamically tables found in multiple columns using Power Query?


I have used the List.Accumulate() to merge mutliple tables. This is the output I've got in this simple example:

[output](https://i.sstatic.net/suU7s.png)

Now, I need a solution to expand all these with a formula, because in real - world I need to merge multiple tables that keep increasing in number (think Eurostat tables, for instance), and modifying the code manually wastes much time in these situations.

I have been trying to solve it, but it seems to me that the complexity of syntax easily becomes the major limitation here. For instance, If I make a new step where I nest in another List.Accumulate() the Table.ExpandTableColumns(), I need to pass inside a column name of an inner table, as a text. Fine, but to drill it down actually, I first need to pass a current column name in [] in each iteration - for instance, Column 1 - and it triggers an error if I store column names to a list because these are between "". I also experimented with TransformColumns() but didn't work either.

Does anyone know how to solve this problem whatever the approach?


Solution

  • See https://blog.crossjoin.co.uk/2014/05/21/expanding-all-columns-in-a-table-in-power-query/

    which boils down to this function

    let Source = (TableToExpand as table, optional ColumnNumber as number) =>
    //https://blog.crossjoin.co.uk/2014/05/21/expanding-all-columns-in-a-table-in-power-query/
    let ActualColumnNumber = if (ColumnNumber=null) then 0 else ColumnNumber,
    ColumnName = Table.ColumnNames(TableToExpand){ActualColumnNumber},
    ColumnContents = Table.Column(TableToExpand, ColumnName),
    ColumnsToExpand = List.Distinct(List.Combine(List.Transform(ColumnContents, each if _ is table then Table.ColumnNames(_) else {}))),
    NewColumnNames = List.Transform(ColumnsToExpand, each ColumnName & "." & _),
    CanExpandCurrentColumn = List.Count(ColumnsToExpand)>0,
    ExpandedTable = if CanExpandCurrentColumn then Table.ExpandTableColumn(TableToExpand, ColumnName, ColumnsToExpand, NewColumnNames) else TableToExpand,
    NextColumnNumber = if CanExpandCurrentColumn then ActualColumnNumber else ActualColumnNumber+1,
    OutputTable = if NextColumnNumber>(Table.ColumnCount(ExpandedTable)-1) then ExpandedTable else ExpandAll(ExpandedTable, NextColumnNumber)
    in OutputTable
    in Source
    

    alternatively, unpivot all the table columns to get one column, then expand that value column

    ColumnsToExpand = List.Distinct(List.Combine(List.Transform(Table.Column(#"PriorStepNameHere", "ValueColumnNameHere"), each if _ is table then Table.ColumnNames(_) else {}))),
    #"Expanded ColumnNameHere" = Table.ExpandTableColumn(#"PriorStepNameHere", "ValueColumnNameHere",ColumnsToExpand ,ColumnsToExpand ),