Created
January 30, 2023 18:06
-
-
Save ncalm/6bb0d889242c569eb473f4d1a1f20f83 to your computer and use it in GitHub Desktop.
Custom M function to simplify table joins in Power Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (LeftTable as table, JoinColumns as list, RightTable as table, optional JoinColumnsRight as list, | |
| optional DuplicateColumnPrefix as text, optional JoinKind as number) => | |
| let | |
| //a function to handle null (optional) parameters | |
| fnIfNull = (arg1, arg2) => if arg1 = null then arg2 else arg1, | |
| //if join kind is null, default to inner join | |
| _JoinKind = fnIfNull(JoinKind, JoinKind.Inner), | |
| //if DuplicateColumnPrefix is null, default to "New ", otherwise concatenate with a space | |
| _DuplicateColumnPrefix = if DuplicateColumnPrefix = null then "New " else DuplicateColumnPrefix & " ", | |
| //Determine which columns are present in both tables | |
| SharedColumnNames = List.Intersect( { Table.ColumnNames(LeftTable) , Table.ColumnNames(RightTable) } ), | |
| //if inner join, remove the join columns from the shared column names, otherwise rename all shared columns | |
| ColumnsToRename = if _JoinKind = JoinKind.Inner then List.Difference( SharedColumnNames, JoinColumns ) else SharedColumnNames, | |
| //build list of lists where each sub-list is {original column name, new column name} | |
| Renames = List.Transform(ColumnsToRename, each {_, _DuplicateColumnPrefix & _}), | |
| //rename the columns in the right table | |
| RightTableRenamed = Table.RenameColumns(RightTable, Renames), | |
| //if JoinColumnsRight is null use JoinColumns | |
| JoinColumnsRightInterim = fnIfNull(JoinColumnsRight, JoinColumns), | |
| /* | |
| If we're using an inner join, just use the JoinColumnsRightInterim (i.e. no renames) | |
| If not, apply the renames to the JoinColumnsRightInterim list using List.ReplaceMatchingItems | |
| */ | |
| _JoinColumnsRight = | |
| if _JoinKind = JoinKind.Inner | |
| then | |
| JoinColumnsRightInterim | |
| else | |
| List.ReplaceMatchingItems(JoinColumnsRightInterim, Renames), | |
| //perform the join | |
| SimpleJoin = | |
| Table.Join( | |
| LeftTable, JoinColumns, | |
| RightTableRenamed, _JoinColumnsRight, | |
| _JoinKind), | |
| Result = SimpleJoin | |
| in | |
| Result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment