条件列中的Powerquery IN运算符

时间:2018-08-20 09:37:19

标签: powerbi powerquery m

如何修改这m个Power BI M代码

= Table.AddColumn(#"PreviousStep", "Tag", each 
     if Text.Contains([Column1]) = "value1" then "bingo" 
else if Text.Contains([Column1]) = "value2" then "bingo"
else if Text.Contains([Column1]) = "value3" then "bingo"
else ["Some other value"])

转换为类似于SQL的一行代码

case when [Column1] in ("value1", "value2", "value3") then "bingo" else "Some other value" end

我不想重复else if行,但采用与

类似的方式
List.Contains({'Value1', 'Value2', 'Value3'}, [Column1])

在这里使用:https://stackoverflow.com/a/51749519/1903793

3 个答案:

答案 0 :(得分:2)

如果要比较整个单词,则应使用List.ContainsAny函数

let
    haystack = #table({"col"}, {{"qwer"}, {"asdf"}, {"zxcv"}, {"zxwecv"}, {"other"}}),
    needles = {"qwer", "zxcv"},
    add = Table.AddColumn(haystack, "Tag", each if List.ContainsAny(needles, {[col]}) then "bingo" else "Some other value")
in
    add


但是如果您搜索单词的一部分,答案就会变得更加复杂

let
    haystack = #table({"col"}, {{"qwer"}, {"asdf"}, {"zxcv"}, {"zxwecv"}, {"other"}}),
    needles = {"we", "as"},
    add = Table.AddColumn(haystack, "Tag", each if List.MatchesAny(needles, (s)=>Text.Contains([col], s)) then "bingo" else "Some other value")
in
    add

答案 1 :(得分:1)

您必须使用List.Transform来生成Text.Contains函数调用,然后使用List.AnyTrue检查Column1是否包含任何文本。

= Table.AddColumn(#"PreviousStep", "Tag", each if List.AnyTrue(List.Transform({"value1", "value2", "value3"}, (s) => Text.Contains([Column1], (s)))) then "bingo" else "Some other value")

结果:

enter image description here

Reference

答案 2 :(得分:0)

或者,如果要返回匹配的字符串,则可以使用List.Accumulate函数:

List.Accumulate(YOUR_LIST_OF_STRINGS, null, (state, current) => if Text.Contains([YOUR COLUMN NAME], current) then current else state)

此方法的唯一缺点是,如果有多个匹配项,则仅返回最后一个...

这是一个更复杂的版本,它返回匹配字符串的列表:

List.Accumulate(YOUR_LIST_OF_STRINGS, {}, (state, current) => if Text.Contains([YOUR COLUMN NAME], current) then List.Combine({{current}, state}) else state)

或者您可以对其进行修改,以使其以字符串等形式返回逗号分隔列表。