18.2Sorting and keeping the top: TOPN

In Excel
ExcelTAKE(SORT(…),N)
Match

You will often need the top of a ranking, such as your five best customers or your three best-selling models. TOPN keeps the first rows of a table according to a measure. Its result is a table, often handed to CALCULATE.

18.2.1The syntax of TOPN

TOPN keeps the first N rows of a table, sorted by an expression.

TOPN( <number>, <table>, <expression>, [<order>] )

It expects the number of rows to keep, then the table, then the expression used to sort its rows, often a measure. The last argument, the order, is optional. Without it, the default order is DESC, and TOPN keeps the largest values. In this lesson, we write it out so that you can see it. With ASC, it keeps the smallest.

Top 2 Revenue = CALCULATE( [Revenue], TOPN( 2, ALL( Customers[Name] ), [Revenue], DESC ) )
Power BI accepts this DAX foryes, Measureyes, Calculated columnno, Calculated tableno, Virtual table
In plain words

“I want the revenue, keeping only the two best customers among all the customers, whatever the customer shown.”

TOPN keeps Orvane and Kumora. CALCULATE adds up their sales, 450,000 and 300,000, that is 750,000.

This is a reproduction of the Power BI interface for teaching purposes. It differs from the real interface.

Practice

Each exercise is solved with the function you just discovered. Two exercises per function, a direct use and a combined use, from easiest to hardest, on data other than the course data. Pick the right formula out of five.

  1. Direct useMeasureDifficulty

    A library already has a “Loans” measure, the sum of the “Loans” column of the “Books” table. Write the “Top 3 Books Loans” measure, the loans of the three most borrowed titles, whatever the title shown.

    Books
    TitleLoans
    Dune30
    Emma25
    Ulysses18
    Candide12

    Which formula should you write for “Top 3 Books Loans”?

  2. Combined useMeasureDifficulty

    A hotel already has a “Nights” measure, the sum of the “Nights” column of the “Rooms” table. Write the “Share of the 2 Least Booked Rooms” measure, the share of these two rooms in the nights of all the rooms, whatever the room shown. The ASC order argument keeps the smallest values.

    Rooms
    RoomNights
    10140
    10212
    10325
    10433

The rest of this lesson is part of izyDAX Pro

You have just read the first section. The next one, its animations, the exercises and the summary are waiting for you with izyDAX Pro, in a single payment.