CountIfs() 在 Power Query M 中等效,计算自身中的每行

CountIfs() Equivalent in Power Query M, counts per row within self

我正在尝试在 Power Query 查询中实现类似于 countifs() 的逻辑,但不是在引用源 table 的摘要 table 中。相反,我想显示所有记录并将其作为另一列(在我的实际用例中这是必要的)。这就是我的意思...

输入数据:

ID | Animal | Color
-- | ------ | -----
 1 | Zebra  | Red
 2 | Zebra  | Blue
 3 | Zebra  | Red
 4 | Zebra  | Red

期望的输出:

ID | Animal | Color | Count of others with same color
-- | ------ | ----- | -------------------------------
 1 | Zebra  | Red   | 3
 2 | Zebra  | Blue  | 1
 3 | Zebra  | Red   | 3
 4 | Zebra  | Red   | 3

在 excel 内联公式中,要计算列 "Count of others with same color" 我会使用

=COUNTIFS([Animal],[@Animal],[Color],[@Color])

如何使用 M 语言在 Power Query 中执行此操作?

对筛选后的 table 使用计数。


自定义列的公式如下所示:

List.Count(
    Table.SelectRows(
        #"Previous Step Name Goes Here",
        (C) => [Animal] = C[Animal] and [Color] = C[Color]
    )[ID]
)

() => 函数构造是必需的,因为您需要引用两个单独的上下文。一个是您正在评估其中的函数的行,另一个是您正在使用 Table.SelectRows 过滤的 table 的行。乍一看有点奇怪,所以我建议搜索“Power Query each function”并阅读一些内容。

注意:将 [ID] 附加到 table 通过选择单个列将其转换为列表。

类似于 Alexis 解决方案,但使用列表函数。

let
    Source = Excel.CurrentWorkbook(){[Name="Test"]}[Content],
    CountCol = Table.AddColumn(Source, "Count", (r) => List.Count(List.PositionOf(Source[Color],r[Color],Occurrence.All)))

in
CountCol

一个名为 "Count" 的新列已添加到 "Source" table。

该函数从 "Source" table 获取每条记录(名为 "r")并将其传递给嵌套函数。

从内部,"List.PositionOf" 获得三个参数:"Source" table 中的 "Color" 列作为列表,字段 "Color" 来自传递记录 ("r") 和第三个可选参数 "Occurrence.All" 强制 return 所有匹配项,而不仅仅是第一个匹配项。

此函数的结果是另一个列表,其中包含整个颜色列表中记录中字段 "Color" 的所有位置。

外部函数 "List.Count" 只计算位置列表的元素,return 是一个整数。

另一个与亚历克西斯的答案略有不同,并借用了丹尼尔的介绍:

let
    aTable = Excel.CurrentWorkbook(){[Name="aTable"]}[Content],
    addCol = Table.AddColumn(aTable, "Count", each Table.RowCount(Table.SelectRows(aTable,(R) => _[key] = R[key])), type number)
in
    addCol

与 Alexis 的区别主要在于不使用 List.Count 函数,而是直接使用 Table.Rowcount,因此无需进行单列选择来转换过滤后的 table 进入列表