適用於:
Databricks SQL
Databricks Runtime
回傳與群組中第二個表達式最小值相關的表達式值。 使用可選的第三個參數, 返回一個最多 limit 包含對應排序表達式最小值的數值的陣列。 語意與集合函數相同max_by,但順序相反。
語法
min_by(expr, ordExpr) [FILTER ( WHERE cond ) ]
適用於:
Databricks SQL
Databricks 執行環境 18.1 及以上版本
min_by(expr, ordExpr, limit) [FILTER ( WHERE cond ) ]
引數
- expr:要回傳其值的表達式。 可以是任何資料型態。
- ordExpr:用來決定最小值(排序鍵)的表達式。 必須是可排序的類型。
-
限制:(可選)
INT代表回傳最大值數的值。 必須大於0且小於或等於100,000。 當函數提供時,會回傳一個最多包含 的limit數值陣列。 - 條件:一個可選的布林運算式,用來過濾用於聚合的列數。
傳回
若無 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)