MAX_BY
functionsupportedCore SQL functionsFinds the row(s) containing the maximum value for a column and returns the value of another column in that row. For example, if a table contains the columns employee_id and salary, MAX_BY(employee_id, salary) returns the value of the employee_id column for the row that has the highest value in the salary column. If multiple rows contain the specified maximum value, the function is non-deterministic. To return values for multiple rows, specify the optional maximum_number_of_values_to_return argument. With this additional argument: - The function returns an ARRAY containing the values of a column for the rows with the highest values of a specified column. - The values in the ARRAY are sorted by their corresponding values in the column containing the maximum values. - If multiple rows contain these highest values, the function is non-deterministic. For example, MAX_BY(employee_id, salary, 5) returns an ARRAY of values of the employee_id column for the five rows containing the highest values in the salary column. The IDs in the ARRAY are sorted by the corresponding values in the salary column. See also: MAX
Syntax
supportedpartialnot supportednot scored
MAX_BY( <col_to_return>, <col_containing_maximum> [ , <maximum_number_of_values_to_return> ] )
Parameters
| Name | Required | Description |
|---|---|---|
col_to_return | required | Column containing the value to return. |
col_containing_maximum | required | Column containing the maximum value. |
maximum_number_of_values_to_return | optional | Constant integer specifying the maximum number of values to return. You must specify a positive number. The maximum number that you can specify is 1000. |
Returns
- If maximum_number_of_values_to_return is not specified, the function returns a value of the same type as col_to_return. - If maximum_number_of_values_to_return is specified, the function returns an ARRAY containing values of the same type as col_to_return. The values in the ARRAY are sorted by their corresponding col_containing_maximum values. For example, MAX_BY(employee_id, salary, 5) returns the IDs of the employees with the highest five salaries, sorted by salary (in descending order).
Usage notes
- The function ignores NULL values in col_containing_maximum.
- If all values in col_containing_maximum are NULL, the function returns NULL (regardless of whether the optional maximum_number_of_values_to_return argument is specified).