Skip to content

Instantly share code, notes, and snippets.

@jcmkk3
Created November 6, 2022 18:31
Show Gist options
  • Save jcmkk3/2e390861440db445e2cdbefaf81863db to your computer and use it in GitHub Desktop.
Save jcmkk3/2e390861440db445e2cdbefaf81863db to your computer and use it in GitHub Desktop.
Simple tidyr like complete function in Power Query M
// Paste this into new blank query called Complete2
(table as table, columnName1 as text, columnName2 as text) as table =>
let
allColumnNames = Table.ColumnNames(table),
otherColumnNames = List.RemoveMatchingItems(allColumnNames, {columnName1, columnName2}),
crossed = Crossing2(table, columnName1, columnName2),
joined = Table.NestedJoin(crossed, {columnName1, columnName2}, table, {columnName1, columnName2}, "crossing", JoinKind.FullOuter),
expanded = Table.ExpandTableColumn(joined, "crossing", otherColumnNames),
reordered = Table.ReorderColumns(expanded, allColumnNames)
in
reordered
// Paste this into new blank query called Crossing2
(table as table, columnName1 as text, columnName2 as text) as table =>
let
// Select the distinct values of each column as its own table
// Add a helper column to each table called "__cross" that has a constant value of 1
column1 = Table.AddColumn(Table.Distinct(Table.SelectColumns(table, {columnName1})), "__cross", each 1),
column2 = Table.AddColumn(Table.Distinct(Table.SelectColumns(table, {columnName2})), "__cross", each 1),
// Perform a cross join on both tables using the helper column
joined = Table.NestedJoin(column1, {"__cross"}, column2, {"__cross"}, "column2", JoinKind.Inner),
expanded = Table.ExpandTableColumn(joined, "column2", {columnName2}, {columnName2}),
// Clean up by removing the helper column from the result
cleaned = Table.RemoveColumns(expanded, {"__cross"})
in
cleaned
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment