Return top value ordered by another column

狂风中的少年 提交于 2019-11-29 17:16:59

Another way to do this is through the use of the TOPN function.

The TOPN function returns entire row(s) instead of a single value. For example, the code

TOPN(1, TableA, TableA[Value])

returns the top 1 row of TableA ordered by TableA[Value]. The Group value associated with that top Value is in the row, but we need to be able to access it. There are a couple of possibilities.


Use MAXX:

Top Group = MAXX(TOPN(1, TableA, TableA[Value]), TableA[Group])

This finds the maximum Group from the TOPN table in the first argument. (There is only one Group value, but this allows us to covert a table into a single value.)


Use SELECTCOLUMNS:

Top Group = SELECTCOLUMNS(TOPN(1, TableA, TableA[Value]), "Group", TableA[Group])

This function usually returns a table (with the columns that are specified), but in this case, it is a table with a single row and a single column, which means the DAX interprets it as just a regular value.

One way to do this is to store the maximum value and use that as a filter condition.

For example,

Top Group =
VAR MaxValue = MAX(TableA[Value])
RETURN MAXX(FILTER(TableA, TableA[Value] = MaxValue), TableA[Group])

or similarly,

Top Group =
VAR MaxValue = MAX(TableA[Value])
RETURN CALCULATE(MAX(TableA[Group]), TableA[Value] = MaxValue)

If there are multiple groups with the same maximum value the measures above will pick the first one alphabetically. If there are multiple and you want to show all of them, you could use a concatenate iterator function:

Top Group =
VAR MaxValue = MAX(TableA[Value])
RETURN CONCATENATEX(
           CALCULATETABLE(
               VALUES(TableA[Group]),
               TableA[Value] = MaxValue
           ),
           TableA[Group],
           ", "
       )

If you changed the 9 in TableA to an 8, this last measure would return A, B rather than A.

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