适用于:
Databricks SQL
Databricks Runtime
返回与组中第二个表达式的最小值关联的表达式的值。 使用可选的第三个参数,返回一个最多对应于 limit 排序表达式最小值的值的数组。 语义与 max_by 具有 相反顺序的聚合函数相同。
语法
min_by(expr, ordExpr) [FILTER ( WHERE cond ) ]
适用于:
Databricks SQL
Databricks Runtime 18.1 及更高版本
min_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 smallest y
> SELECT min_by(x, y) FROM VALUES (('a', 10)), (('b', 50)), (('c', 20)) AS tab(x, y);
a
-- Return the values of x for the rows with the 2 smallest y values
> SELECT min_by(x, y, 2) FROM VALUES (('a', 10)), (('b', 50)), (('c', 20)) AS tab(x, y);
[a, c]
-- Return the lowest-paid employee in each department
> SELECT department, min_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 Bob
Sales Dan
-- Return the 2 lowest-paid employees in each department
> SELECT department, min_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 [Bob, Carol]
Sales [Dan, Eve]
> SELECT min_by(x, y COLLATE UTF8_LCASE) FROM VALUES (('a', 'X')), (('b', 'x')), (('c', 'Z')) AS tab(x, y);
a (or b)