Power BI DAX计数发生

时间:2019-10-06 19:14:03

标签: powerbi dax

我有以下数据集:

KEY                    CNT
A-S000218691600_14       1
A-S000218691600_14       2
A-S000218691600_14       3
A-S000218696400_1        1
A-S000218691600_14       4
A-S000218691600_14       5
A-S000218691600_14       6
A-S000218691600_14       7
A-S000218691600_14       8
A-S000218693200_1        1
A-S000218691600_14       9
A-S000218691600_14      10
A-S000218691600_14      11
A-S00021869245175.29_1   1
A-S000218691600_14      12
A-S000218691600_14      13
A-S00021869110339.26_1   1
A-S000218691600_14      14
A-S000218696400_1        2
A-S000218691600_7        1
A-S000218691600_7        2
A-S000218691600_7        3
A-S000218691600_7        4
A-S000218691600_7        5
A-S000218691600_7        6
A-S000218691600_7        7
A-S0002186917600_1       1

在Excel中,我可以使用=COUNTIF(A$2:A2,A2)创建CNT列,但在DAX中不能得到相同的结果。 我尝试了以下操作,但未生成相同的输出:

 cnt = calculate(
     COUNTROWS(table),
     filter(
        ALLEXCEPT(table, table[key]),
        table[key]=EARLIER(table[key])
    )
 )

有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

您需要另外一列来标识每个键在该列中的位置。

在查询编辑器中添加索引列:

//Table1
let
    Source = MyTable,
    #"Added Index" = Table.AddIndexColumn(Source, "Index", 1, 1)
in
    #"Added Index"

现在您可以创建以下计算列:

cnt = 
    CALCULATE ( 
        COUNTROWS ( Table1 ),
        FILTER ( 
            ALLEXCEPT ( Table1, Table1[Key] ),
            Table1[Index] <= EARLIER ( Table1[Index] )
        )
    )

工作示例PBIX文件:https://pwrbi.com/so_58260475/

编辑:

要回答有关大型数据集性能不佳的查询:您可以在查询编辑器中而不是DAX中实现所需的功能,方法是对每个Key项进行分区,建立索引,然后重新组合分区:

let
    Source = MyTable,
    #"Added Index" = Table.AddIndexColumn(Source, "Index", 1, 1),
    #"Partition Keys" = Table.Group(#"Added Index", {"Key"}, {{"Data", each Table.AddIndexColumn(Table.Sort(_, {"Index", Order.Ascending}),"cnt",1,1), type table}}),
    #"Combine Partitions" = Table.Combine(#"Partition Keys"[Data])
in
    #"Combine Partitions"

此测试非常快,有40万行。