【问题标题】:How to join two tables in PowerQuery with one of many columns matching?如何将 Power Query 中的两个表与多个匹配的列之一连接起来?
【发布时间】:2019-02-12 16:03:38
【问题描述】:

假设我们有两个 PowerQuery 查询:

  1. 名为Query1 的查询,列Col1_1Col1_2
  2. 名为Query2 的查询,列Col2_1Col2_2

我知道可以将这两个查询与这样的合并查询结合起来:

let
    Source = Table.NestedJoin(Query1,{"Col1_1", "Col1_2"},Query2,{"Col2_1", "Col2_2"},"Query2",JoinKind.LeftOuter)
in
    Source

在 SQL 中,这可以表示为

SELECT
    *
FROM
    Query1
    LEFT JOIN Query2 ON Query1.Col1_1 = Query2.Col2_1 AND Query1.Col1_2 = Query2.Col2_2

问题:如果两列中至少有一列匹配,是否可以连接这两个查询? 在 SQL 中,这可以表示为

SELECT
    *
FROM
    Query1
    LEFT JOIN Query2 ON Query1.Col1_1 = Query2.Col2_1 OR Query1.Col1_2 = Query2.Col2_2

【问题讨论】:

    标签: excel powerquery m


    【解决方案1】:

    不进行表连接,另一种可能性是使用您想要的逻辑添加自定义列:

    Table.AddColumn(Source, "JoinQuery2",
        (Q1) => Table.SelectRows(Query2,
                    each Q1[Col1_1] = [Col2_1] or Q1[Col1_2] = [Col2_2]
                )
    )
    

    然后,您可以像进行合并一样展开这列表格。


    我从这篇博文中得到了这个想法: Join Conditions In Power Query, Part 1

    【讨论】:

      【解决方案2】:

      据我所知,没有选项可以更改 PQ 中 Join 函数中的默认匹配方法。但是,您可以对所需的每一列进行两次连接,然后组合这些连接的结果。

      当 col1 和 col2 都匹配时,这将导致重复匹配,我不确定这是否是预期的结果。如果没有,您可以使用 PQ 设置索引来捕获这些重复项并将它们删除。

      假设 Query2 也添加了一个如下所示的索引:

      let
          Source = Query1,
          #"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1),
          #"Merged Queries" = Table.NestedJoin(#"Added Index",{"col1"},Query2,{"col1"},"col1Join",JoinKind.LeftOuter),
          #"Merged Queries1" = Table.NestedJoin(#"Merged Queries",{"col2"},Query2,{"col2"},"col2Join",JoinKind.LeftOuter),
          #"Added Custom" = Table.AddColumn(#"Merged Queries1", "MergeTables", each Table.Combine({[col1Join],[col2Join]})),
          #"Expanded Custom" = Table.ExpandTableColumn(#"Added Custom", "MergeTables", {"col1", "col2", "Index"}, {"Query2.col1", "Query2.col2", "Query2.Index"}),
          #"Removed Duplicates" = Table.Distinct(#"Expanded Custom", {"Index", "Query2.Index"}),
          #"Removed Columns" = Table.RemoveColumns(#"Removed Duplicates",{"Index", "col1Join", "col2Join", "Query2.Index"})
      in
          #"Removed Columns"
      

      不是一个非常可扩展的解决方案,但我认为它可以正常工作?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-05
        • 1970-01-01
        • 1970-01-01
        • 2019-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多