Power Query匹配条件时返回多列及空值转null问题
解决Power Query中匹配SectionName并同步提取Filter列的问题
问题分析
原代码仅能提取匹配的SectionName列,无法同步获取对应的Filter值;且无匹配时会返回空白字符串而非null,原因是Text.Combine处理空列表时默认返回空白。
修改后的M代码(支持多匹配合并)
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"Source", type text}}), #"Added Matching Columns" = Table.AddColumn(#"Changed Type", "MatchResult", (x) => let MatchedRows = Table.SelectRows(Table25, each Text.Contains(x[Source], [SectionName], Comparer.OrdinalIgnoreCase)), HasMatch = Table.RowCount(MatchedRows) > 0 in if HasMatch then [ SectionName = Text.Combine(MatchedRows[SectionName], ", "), Filter = Text.Combine(List.ReplaceNull(MatchedRows[Filter], ""), ", ") ] else [SectionName = null, Filter = null] ), #"Expanded MatchResult" = Table.ExpandRecordColumn(#"Added Matching Columns", "MatchResult", {"SectionName", "Filter"}, {"SectionName", "Filter"}) in #"Expanded MatchResult"
简化版(单匹配场景)
如果确定每条Source记录仅匹配一个SectionName,可使用更简洁的写法:
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"Source", type text}}), #"Added Matching Columns" = Table.AddColumn(#"Changed Type", "MatchResult", (x) => let // 用{0}?取第一条匹配记录,?避免无匹配时报错 MatchedRow = Table.SelectRows(Table25, each Text.Contains(x[Source], [SectionName], Comparer.OrdinalIgnoreCase)){0}? in if MatchedRow <> null then [SectionName = MatchedRow[SectionName], Filter = MatchedRow[Filter]] else [SectionName = null, Filter = null] ), #"Expanded MatchResult" = Table.ExpandRecordColumn(#"Added Matching Columns", "MatchResult", {"SectionName", "Filter"}, {"SectionName", "Filter"}) in #"Expanded MatchResult"
关键改进点
- 同步提取Filter列:通过构建包含
SectionName和Filter的记录,再展开为独立列,实现两列同步匹配。 - 空白转null:通过
Table.RowCount判断是否有匹配结果,无匹配时直接返回null,替代Text.Combine生成的空白字符串。 - 处理Filter列null值:用
List.ReplaceNull将Filter列的null转为空字符串,避免Text.Combine运行报错。
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

