MAX_BY
Applies to: ✅ Data 360 SQL ✅ Tableau Hyper API
Returns the <value> from the row whose <key> is greatest among all rows in the aggregate (or within each group when used with GROUP BY).
<value>: Any expression whose result is returned when its row wins the comparison. The aggregate result type matches this expression’s type.<key>: The expressionMAX-BYuses to order the rows. The type must support comparison.
IGNORE NULLS: Skips rows containingNULLvalues. This is the default behavior.RESPECT NULLS: Considers rows containginNULLvalues.
The <value> from the row with the maximum <key> among considered rows.
Null handling:
- You can combine
max_bywith other aggregates,GROUP BY,HAVING, subqueries, and expressions in the arguments (for example,max_by(upper(name), score * 2)). max_byonly supports a single value to sort on. To sort using multiple sort criteria, use FIRST_VALUE WITHIN GROUP.- If the aggregate has no input rows (empty table or empty group), the result is
NULL. - If every row has a
NULLkey, those rows are skipped; if no row has a non-NULLkey, the result isNULL. - If the winning row’s
<value>isNULL, the result isNULL(the key still determines which row wins).
Tie-breaking: If multiple rows share the same maximum key, one of the tied <value> results is returned; which tied row wins is implementation-dependent.
DISTINCTis not supported (for example,max_by(DISTINCT name, score)is a syntax error).- Rows with a
NULL<key>are ignored when searching for the maximum key. - You can combine
max_bywith other aggregates,GROUP BY,HAVING, subqueries, and expressions in the arguments (for example,max_by(upper(name), score * 2)).
Returns the name and score from the row with the highest score.
Returns 'David'.
Uses GROUP BY so each region gets its own arg-max product and returns the regions and their maximum revenue.
Returns one row per region. For example South / 'A' and North / 'B'.
Keys that are NULL are skipped. In this example, the largest non-NULL key is 15, and that row’s value is NULL.
Returns NULL.