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:
Product | SalesAmount |
Product A | 500 |
Product B | 300 |
Product C | 700 |
Product D | 200 |
Product E | 400 |
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:
Product | SalesAmount |
Product C | 700 |
Product A | 500 |
Product E | 400 |
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
Product | SalesAmount | Category | Region |
Product C | 700 | Electronics | North |
Product A | 500 | Furniture | South |
Product E | 400 | Electronics | East |
Product B | 600 | Furniture | West |
Product D | 800 | Electronics | North |
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:
Product | SalesAmount | Category | Region |
Product D | 800 | Electronics | North |
Product C | 700 | Electronics | North |
Product B | 600 | Furniture | West |
This approach ensures that you can include multiple fields in your TOPN results, making your analysis more comprehensive.