Code Generator | M (Power Query)

Merging Tables in Power Query

This code snippet demonstrates how to merge two tables in Power Query using multiple columns and return only the matching records.


Empty image or helper icon

Prompt

Can you provide a Power Query M code snippet that merges two tables based on two or more columns and returns only matching records?

Answer

Sure! Here's a succinct Power Query M code snippet that merges two tables based on two or more columns and returns only matching records:

let
    // Source tables
    table1 = #table({"Key1", "Key2", "Column1"}, {{1, "A", "Value1"}, {2, "B", "Value2"}}),
    table2 = #table({"Key1", "Key2", "Column2"}, {{1, "A", "Value3"}, {3, "C", "Value4"}}),

    // Merge tables
    mergedTable = Table.Join(table1, {"Key1", "Key2"}, table2, {"Key1", "Key2"}),

    // Select columns to keep in the final result
    resultTable = Table.SelectColumns(mergedTable,{"Key1", "Key2", "Column1", "Column2"})
in
    resultTable

This code creates two source tables (table1 and table2) with matching and non-matching records. The tables are then merged using the Table.Join function, specifying the key columns (Key1 and Key2) in both tables. Finally, the Table.SelectColumns function is used to select the desired columns (Key1, Key2, Column1, and Column2) in the result table.

Example usage:

  • table1:
| Key1 | Key2 | Column1 |
|------|------|---------|
|  1   |  A   | Value1  |
|  2   |  B   | Value2  |
  • table2:
| Key1 | Key2 | Column2 |
|------|------|---------|
|  1   |  A   | Value3  |
|  3   |  C   | Value4  |
  • Result (resultTable):
| Key1 | Key2 | Column1 | Column2 |
|------|------|---------|---------|
|  1   |  A   | Value1  | Value3  |

The resulting table contains only the matching records based on the Key1 and Key2 columns.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

The provided code showcases the process of merging two tables (table1 and table2) based on two or more columns (Key1 and Key2). It uses the Table.Join function to merge the tables and the Table.SelectColumns function to select the desired columns in the resulting table. The output is a new table (resultTable) that contains only the matching records from both tables.