Suppose I have a table as follows:
TableA =
DATATABLE (
"Year", INTEGER,
"Group", STRING,
"Value", DOUBLE,
{
{ 2015, "A", 2 },
{ 2015, "B", 8 },
{ 2016, "A", 9 },
{ 2016, "B", 3 },
{ 2016, "C", 7 },
{ 2017, "B", 5 },
{ 2018, "B", 6 },
{ 2018, "D", 7 }
}
)
I want a measure that returns the top Group
based on its Value
that work inside or outside a Year
filter context. That is, it can be used in a matrix visual like this (including the Total row):
It's not hard to find the maximal value using DAX:
MaxValue = MAX(TableA[Value])
or
MaxValue = MAXX(TableA, TableA[Value])
But what is the best way to look up the Group
that corresponds to that value?
I've tried this:
Top Group = LOOKUPVALUE(TableA[Group],
TableA[Year], MAX(TableA[Year]),
TableA[Value], MAX(TableA[Value]))
However, this doesn't work for the Total row and I'd rather not have to use the Year
in the measure if possible (there are likely other columns to worry about in a real scenario).
Note: I am providing a couple solutions in the answers below, but I'd love to see any other approaches as well.
Ideally, it would be nice if there were an extra argument in the MAXX
function that would specify which column to return after finding the maximum, much like the MAXIFS Excel function has.
One way to do this is to store the maximum value and use that as a filter condition.
For example,
or similarly,
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:
If you changed the
9
inTableA
to an8
, this last measure would returnA, B
rather thanA
.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 codereturns the top 1 row of
TableA
ordered byTableA[Value]
. TheGroup
value associated with that topValue
is in the row, but we need to be able to access it. There are a couple of possibilities.Use
MAXX
:This finds the maximum
Group
from theTOPN
table in the first argument. (There is only oneGroup
value, but this allows us to covert a table into a single value.)Use
SELECTCOLUMNS
: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.