max_by 聚合函數

適用於:核取記號為「是」Databricks SQL 核取記號為「是」Databricks Runtime

回傳與群組中第二個表達式最大值相關的表達式值。 使用可選的第三個參數,回傳一個最多為 的 limit 陣列,對應排序表達式的最大值。

語法

max_by(expr, ordExpr) [FILTER ( WHERE cond ) ]

適用於:勾選標記為是 Databricks SQL 勾選標記為是 Databricks 執行環境 18.1 及以上版本

max_by(expr, ordExpr, limit) [FILTER ( WHERE cond ) ]

您也可以使用 子句,將此函式叫用為OVER式。

引數

  • 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 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)