如何在Power Query中实现多表多列层级查找
在Power Query中实现层级查找(等效Excel嵌套IFERROR+VLOOKUP)
需求说明
实现与Excel公式=IFERROR(IFERROR(VLOOKUP([@[Account Name]],Table15,5,FALSE),VLOOKUP([@Industry],Table14,2,FALSE)),"Industry Unknown")完全等效的逻辑:
- 优先通过主表的Account Name列匹配「Account to Segment Mappings」表,获取「Customer Segment」
- 若匹配失败,通过主表的Industry列匹配「Industry to Segment Mappings」表
- 若两次匹配都失败,返回固定文本
"Industry Unknown"
实现方案
利用M语言的try...otherwise结构实现层级容错逻辑,以下提供两种写法:
写法1:基于你已掌握的Table.SelectRows
在主表中添加自定义列,公式如下:
try (Table.SelectRows(#"Account to Segment Mappings", each [Account Name] = [Account Name])){0}[Customer Segment] otherwise try (Table.SelectRows(#"Industry to Segment Mappings", each [Industry] = [Industry])){0}[Customer Segment] otherwise "Industry Unknown"
- 外层
try...otherwise:先尝试从Account映射表匹配,失败则进入下一层 - 内层
try...otherwise:尝试从Industry映射表匹配,失败则返回指定文本 {0}[Customer Segment]:从匹配到的行中提取目标列值
写法2:更高效的Table.Lookup(推荐)
Table.Lookup是Power Query专为单值查找设计的函数,性能优于Table.SelectRows,公式如下:
try Table.Lookup(#"Account to Segment Mappings", "Account Name", [Account Name], "Customer Segment") otherwise try Table.Lookup(#"Industry to Segment Mappings", "Industry", [Industry], "Customer Segment") otherwise "Industry Unknown"
Table.Lookup参数说明:Table.Lookup(查找表, 查找表的键列名, 待匹配的值, 返回列名)
操作步骤
- 确保主表、「Account to Segment Mappings」、「Industry to Segment Mappings」三张表已加载到Power Query编辑器
- 选中主表,点击顶部菜单栏「添加列」→「自定义列」
- 在弹出的公式框中粘贴上述任意一种代码,点击「确定」
- 将生成的自定义列重命名为
Customer Segment
验证结果
根据你提供的示例数据,最终主表结果如下:
| Account Name | Industry | Customer Segment |
|---|---|---|
| ABC Bank | Financial | Financial |
| Z Company | Merchants | Merchant & Commerce |
| D Company | Merchants | Digital Partner |
| A Company | Energy/Utilities | Merchant & Commerce |
内容的提问来源于stack exchange,提问作者Vinayak Aggrawal
相关产品推荐
相关产品推荐

