Power BI DAX: TOPN, ASC, DESC

TopNValues =
TOPN(<N_Value>, <Table>, <OrderBy_Expression>, [<Order>[, <OrderBy_Expression>, [<Order>]]…])

The TOPN function in DAX (Data Analysis Expressions) is used to return the top 'N' rows from a specified table or expression based on a given order. This function is particularly useful when you want to focus on the highest (or lowest) values of a specific column or expression output.

Scenario

You have a sales dataset and you want to identify the top 3 products with the highest sales amounts.

Sample Data

A simplified version of your sales data:

ProductSalesAmount
Product A500
Product B300
Product C700
Product D200
Product E400

DAX Expression

To find the top 3 products by sales amount, you can use the following DAX expression:

Top3Products =
TOPN ( 3, Sales, Sales[SalesAmount], DESC )

Explanation

• TOPN(3, Sales, Sales[SalesAmount], DESC): This function returns the top 3 rows from the Sales table, ordered by the SalesAmount column in descending order.

Result

Using the sample data, the expression will return the following table:

ProductSalesAmount
Product C700
Product A500
Product E400

This approach helps you quickly identify the top-performing products based on sales, allowing for more focused analysis and decision-making.


Advanced Exercise

Scenario

We have a sales dataset with the following fields:

  • Product,

  • SalesAmount,

  • Category, and

  • Region.

Sample Data

ProductSalesAmountCategoryRegion
Product C700ElectronicsNorth
Product A500FurnitureSouth
Product E400ElectronicsEast
Product B600FurnitureWest
Product D800ElectronicsNorth

DAX Expression

To get the top 3 products by SalesAmount, including Category and Region, you can use the following DAX expression:

Top3Products =
TOPN (
    3,
    Sales,
    Sales[SalesAmount], DESC,
    Sales[Category], ASC,
    Sales[Region], ASC
)

Explanation

• 3: Specifies the number of top rows to return.

• Sales: The table from which to return the top rows.

• Sales[SalesAmount], DESC: Orders the rows by SalesAmount in descending order.

• Sales[Category], ASC: Adds a secondary order by Category in ascending order.

• Sales[Region], ASC: Adds a tertiary order by Region in ascending order.

Result

Using the above expression, the result will include the top 3 products along with their SalesAmount, Category, and Region:

ProductSalesAmountCategoryRegion
Product D800ElectronicsNorth
Product C700ElectronicsNorth
Product B600FurnitureWest

This approach ensures that you can include multiple fields in your TOPN results, making your analysis more comprehensive.