PowerQuery批量合并列需求:99+列自动关联另一数据集
PowerQuery 批量迭代合并列实现方案
核心思路
用List.Accumulate函数迭代主表的目标列,自动完成每一列的嵌套连接与字段展开,替代手动重复编写的合并/展开代码。
具体实现代码
假设你的主表是#"Changed Type",关联表是Format2,需要展开的字段固定为{"Total of reporting period", "Total of the comparison period", "Absolute difference"},按以下方式修改M代码:
let Source = #"Changed Type", // 定义需要处理的列名列表,根据实际场景选一种即可 // 示例1:取主表所有列(如果主表只有需要合并的列) TargetColumns = Table.ColumnNames(Source), // 示例2:排除不需要处理的列(比如"日期"这类固定列) // TargetColumns = List.RemoveItems(Table.ColumnNames(Source), {"日期"}), // 示例3:只保留以BA开头的列(匹配你示例里的列名规则) // TargetColumns = List.Select(Table.ColumnNames(Source), each Text.StartsWith(_, "BA")), // 迭代执行合并与展开操作 FinalTable = List.Accumulate( TargetColumns, Source, (currentTable, colName) => let // 执行嵌套连接 Joined = Table.NestedJoin( currentTable, {colName}, Format2, {"Account Number"}, colName & ".", JoinKind.LeftOuter ), // 展开关联表的三个字段,自动生成和手动操作一致的列名 Expanded = Table.ExpandTableColumn( Joined, colName & ".", {"Total of reporting period", "Total of the comparison period", "Absolute difference"}, {colName & "..Total of reporting period", colName & "..Total of the comparison period", colName & "..Absolute difference"} ) in Expanded ) in FinalTable
代码说明
TargetColumns:根据你的数据集结构选择对应的列筛选逻辑,确保只包含需要关联的列。List.Accumulate:作为迭代核心,会依次对每个目标列执行连接+展开操作,每次迭代的结果作为下一次操作的基础表,自动完成99+列的批量处理。- 字段命名:展开后的列名完全遵循你手动编写的
列名..字段名格式,无需额外调整。
注意事项
- 确保主表目标列和关联表
Account Number字段的数据类型一致,否则会出现匹配失败的情况。 - 如果数据集行数较多,建议先过滤掉不必要的行再执行批量合并,避免内存占用过高。
内容的提问来源于stack exchange,提问作者StijnvdBerg
相关产品推荐
相关产品推荐

