Power Query:匹配列表项与列值子串,返回对应新市场名称
问题解决:提取并拼接匹配的新市场名称
需求说明
现有Markets表,其Column 1列同时包含新旧市场名称;另有一个独立查询加载的NewMarkets列表,存储所有新市场名称。需要实现:遍历Markets表的每个Column 1值,查找其中包含的NewMarkets列表项,将所有匹配的新名称拼接后返回;若未找到匹配项,则返回Column 1的原数值。
用户尝试的错误公式
用户在Markets表中添加自定义列时使用了以下公式,但仅返回Column 1原数值:
let CurrentValue = [Column 1], Markets = #"NewMarkets", MarketFound = List.Select(Markets, each Text.Contains(CurrentValue, _)), Result = if List.Count(MarketFound) > 0 then MarketFound{0} else CurrentValue in CurrentValue
错误原因
- 公式最后返回的是
CurrentValue而非计算后的Result,导致无论匹配与否都返回原数值 - 仅取了第一个匹配项
MarketFound{0},未实现所有匹配项的拼接
示例数据与期望结果
| Column 1 | Expected Value |
|---|---|
| Clothing, Textiles, Cloth, Garments | Textiles, Cloth, Garments |
| Steel, Plastics, Manufacturing | Steel, Plastics |
| Offshore, O&G-Refineries | O&G-Refineries |
| Renewables | Renewables |
注:示例中NewMarkets列表内容为{"Textiles", "Cloth", "Garments", "Steel", "Plastics", "O&G-Refineries"}
正确的自定义列公式
使用以下Power Query M公式添加自定义列,可实现需求:
let CurrentValue = [Column 1], // 获取NewMarkets列表 NewMarketList = #"NewMarkets", // 筛选出CurrentValue中包含的所有新市场名称 MatchedMarkets = List.Select(NewMarketList, each Text.Contains(CurrentValue, _)), // 拼接匹配项,无匹配则返回原数值 Result = if List.Count(MatchedMarkets) > 0 then Text.Combine(MatchedMarkets, ", ") else CurrentValue in Result
公式说明
NewMarketList = #"NewMarkets":引用独立加载的新市场列表MatchedMarkets = List.Select(...):筛选出当前Column 1值中包含的所有新市场名称Text.Combine(MatchedMarkets, ", "):用逗号加空格拼接所有匹配的新市场名称- 最后返回计算后的
Result,而非原数值
内容的提问来源于stack exchange,提问作者Stephen Trippy
相关产品推荐
相关产品推荐

