DAX equivalent of Excel PERCENTRANK.INC per category

╄→尐↘猪︶ㄣ 提交于 2019-12-24 17:46:34

问题


I would like to calculate in DAX equivalent of Excel function PERCENTRANK.INC but per Category. I admit that I do not know even how to calculate it for Category. Any hints will be highly appreciated.

Here is M code for sample data:

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcisqzSwpVtJRSiwoyEkF0oZKsTpIwkmJeUAIZJigipfn56QlpRYVVQLZpqhSyRlQcWOweFhqempJYlJOKlgusagovwTIMMKUK8gvSSzJhzsBRS4/LzM/D0ibo1qFw9HILogFAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [Category = _t, Product = _t, Amount = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Amount", Int64.Type}})
in
    #"Changed Type"

回答1:


The measure below would produce the desired result. As there is no PERCENTRANK function in DAX, you can manually calculate it from the results of RANKX and COUNTROWS.

Percent Rank Within Category = 
IF (
    -- This calculation only makes sense if there is only one product
    -- in the current filter context. If there are more than one products
    -- or no product in the filters, BLANK should be returned.
    HASONEVALUE ( MyTable[product] ),

    -- Get all products which belong to the same parent category with
    -- the product currently being filtered
    VAR tbl = CALCULATETABLE (

        -- all products, in the modified filter context of...
        VALUES ( MyTable[product] ),

        -- no filter on product
        REMOVEFILTERS ( MyTable[product] ),

        -- and under the same parent category
        VALUES ( MyTable[Category] )
    )

    RETURN
    CALCULATE (
        -- PERCENTRANK = (<rank of product> - 1)
        --               / (<total N of products> - 1)
        DIVIDE (

            -- Sales rank of each product in ascending order
            RANKX (
                tbl,
                CALCULATE ( SUM ( MyTable[Amount] ) ), ,
                ASC
            ) - 1,

            -- Total number of products
            COUNTROWS ( tbl ) - 1,

            -- When there is only one product, it should return 1
            1
        )
    )
)




回答2:


Here's how I would write it. Very similar to Kosuke's answer but maybe more readable.

Percent Rank =
VAR ProductsInCategory =
    CALCULATETABLE ( VALUES ( MyTable[Product] ), ALLSELECTED ( MyTable[Product] ) )
VAR RankProduct =
    RANKX ( ProductsInCategory, [Sales],, ASC )
RETURN
    IF (
        HASONEVALUE ( MyTable[Product] ),
        DIVIDE ( RankProduct - 1, COUNTROWS ( ProductsInCategory ) - 1 )
    )


来源:https://stackoverflow.com/questions/59102487/dax-equivalent-of-excel-percentrank-inc-per-category

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!