如何根据条件分组统计?

How to group and count based on condition?

示例数据

id  article   price
1   grapes    2
1   oranges   1
1   bananas   0
2   bananas   0
3   grapes    2
3   oranges   1
4   bananas   0
4   peaches   0

我需要先按 id 分组,然后计算价格总和为 $1 或更多的 id。在这种情况下,所需的结果将是 2([​​=11=] 1 和 3)。 id 2 只是香蕉,价格为 0 美元,因此不算在内 id 4 是香蕉和桃子,价格也是 0 美元。

您要找的公式是:

ID Count =
VAR idgroup =
    GROUPBY (
        Fruits,
        Fruits[id],
        "Sum Price",
            SUMX (
                CURRENTGROUP (),
                Fruits[price]
            )
    )
RETURN
    COUNTX (
        FILTER (
            idgroup,
            [Sum Price] > 1
        ),
        [Sum Price]
    )


Groupby Aggregations
Refer to columns of a table variable

首先,创建价格总和的度量:

Price Sum = SUM( fruits[price] )

然后:

Id Count = SUMX( VALUES( fruits[id]), IF ( [Price Sum] > 1, 1))

结果:

工作原理:

使用 VALUES 函数,我们创建了一个唯一 ID 列表。然后 SUMX 迭代列表,计算每个 id 的总和,检查它是否 > 1,如果是,则将其添加到结果中。