You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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"

关键改进点

  1. 同步提取Filter列:通过构建包含SectionName和Filter的记录,再展开为独立列,实现两列同步匹配。
  2. 空白转null:通过Table.RowCount判断是否有匹配结果,无匹配时直接返回null,替代Text.Combine生成的空白字符串。
  3. 处理Filter列null值:用List.ReplaceNull将Filter列的null转为空字符串,避免Text.Combine运行报错。

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:05:21