适用于:
Databricks SQL
Databricks Runtime
返回与组中第二个表达式的最大值关联的表达式的值。 使用可选的第三个参数,返回一个最多对应于 limit 排序表达式最大值的值的数组。
语法
max_by(expr, ordExpr) [FILTER ( WHERE cond ) ]
适用于:
Databricks SQL
Databricks Runtime 18.1 及更高版本
max_by(expr, ordExpr, limit) [FILTER ( WHERE cond ) ]
参数
- expr:要返回其值的表达式。 可以是任何数据类型。
- ordExpr:用于确定最大值(排序键)的表达式。 必须是可排序的类型。
-
limit:(可选) 一个
INT值,表示要返回的最大值数。 必须大于 0 且小于或等于 100,000。 如果提供,该函数将返回一个最大limit值数组。 - cond:可选的布尔表达式,用于筛选用于聚合的行。
返回
没有 limit:结果类型与类型 expr匹配。 如果多个行具有相同的最大值 ordExpr,则结果是不确定的。
使用 limit:一个 ARRAY 值,其元素类型与类型 expr匹配。 数组包含最多 limit 包含元素。 不包括与 NULL 排序对应的值。 如果所有排序值都是 NULL,则结果为 NULL。 如果多个行共享相同的最大值,则函数是不确定的。
注释
对于某些 STRING 排序规则,例如 UTF8_LCASE,结果也可能是不确定的。
示例
以下示例用内联表定义了它们的输入行,所以你可以在不创建表的情况下运行它们。 在 FROM VALUES ... AS tab(x, y)中, tab 是表别名, x 和 y 是其列名。 请参阅 VALUES 条款。
-- Return the value of x for the row with the largest y
> SELECT max_by(x, y) FROM VALUES (('a', 10)), (('b', 50)), (('c', 20)) AS tab(x, y);
b
-- Return the values of x for the rows with the 2 largest y values
> SELECT max_by(x, y, 2) FROM VALUES (('a', 10)), (('b', 50)), (('c', 20)) AS tab(x, y);
[b, c]
-- Return the highest-paid employee in each department
> SELECT department, max_by(name, salary)
FROM VALUES ('Alice', 'Engineering', 150000), ('Bob', 'Engineering', 120000), ('Carol', 'Engineering', 135000), ('Dan', 'Sales', 90000), ('Eve', 'Sales', 110000) AS employees(name, department, salary)
GROUP BY department ORDER BY department;
Engineering Alice
Sales Eve
-- Return the 2 highest-paid employees in each department
> SELECT department, max_by(name, salary, 2)
FROM VALUES ('Alice', 'Engineering', 150000), ('Bob', 'Engineering', 120000), ('Carol', 'Engineering', 135000), ('Dan', 'Sales', 90000), ('Eve', 'Sales', 110000) AS employees(name, department, salary)
GROUP BY department ORDER BY department;
Engineering [Alice, Carol]
Sales [Eve, Dan]
> SELECT max_by(x, y COLLATE UTF8_LCASE) FROM VALUES (('a', 'X')), (('b', 'x')), (('c', 'v')) AS tab(x, y);
a (or b)