Power Query - 自定义函数计数

Power Query - Count if custom function

.

我想创建一个自定义函数,我在其中传入一个 table、一列和一个值,它计算满足这些条件的所有行。

到目前为止我有

let 
    fCountif = (tbl as table, col as text, value as any) as number =>
    let
        select_rows = Table.SelectRows(tbl, each [col] = value),
        count_rows = Table.RowCount(select_rows)
    in
        count_rows
in
    fCountif

但是我 运行 遇到了各种各样的问题。第一个是调用函数来测试它,当我为 Table 名称传入一个字符串时,它会向函数发送一个文字字符串,而不是将其转换为 table。这可能只是通过查询编辑器按钮调用它时的一个问题,并且在我的其余 M 代码中使用该函数时应该会自行解决。

其次是如何将col值传入函数的[col]部分。我见过 other examples 中使用的胖火箭,即 [column name] <= col,但就是无法让它工作。

我正在努力了解函数,并且在 vba 中很乐意table 这样做,所以如果您有任何提示,请大声说出来。这方面的文档很难获得。干杯。

这应该有效:

let 
  fCountif = (tbl as table, col, value) => 
  let 
   select_rows = Table.SelectRows(tbl, Expression.Evaluate("each "&Text.Replace("["&col&"] = *"&value&"*","*",""""))),
   count_rows = Table.RowCount(select_rows) 
  in count_rows 
in fCountif

可以将表视为记录列表,其中每条记录都是一行。在Table.AddColumn和Table.SelectRows的函数中,[col]Record.Field(_, "col")的一种较短的写法,它访问记录的"col"字段。

这是编写函数的一种方法:

let 
    fCountif = (tbl as table, col as text, value as any) as number =>
    let
        select_rows = Table.SelectRows(tbl, each Record.Field(_, col) = value),
        count_rows  = Table.RowCount(select_rows)
    in
        count_rows
in
    fCountif