类别:

/sql-reference/functions-aggregation`(通用)、:doc:/sql-reference/functions-window`

MEDIAN

确定一组值的中位数。

语法

聚合函数

MEDIAN( <expr> )

窗口函数

MEDIAN( <expr> ) OVER ( [ PARTITION BY <expr2> ] )

实参

expr

The expression must evaluate to a numeric data type (INTEGER, FLOAT, DECIMAL, or equivalent).

返回

Returns a FLOAT or DECIMAL (fixed-point) number, depending upon the input.

使用说明

  • 如果非 NULL 值的数量是大于或等于 1 的奇数,则返回非 NULL 值的中位数(“中心”)值。

  • 如果非 NULL 值的数量是偶数,则返回的值等于两个中心值的平均值。例如,如果值为 1、3、5 和 20,则返回 4(3 和 5 的平均值)。

  • 如果所有值均为 NULL,则返回 NULL。

  • 如果非 NULL 值的数量为 0,则返回 NULL。

  • 此函数不支持 DISTINCT。

  • 当此函数作为窗口函数调用时,它不支持:

    • OVER 子句中的 ORDER BY 子句。

    • 显式窗口框架。

示例

这显示了该函数的使用方法。

创建一个空表。

CREATE OR REPLACE TABLE aggr (k INT, v DECIMAL(10,2));

Get the MEDIAN value for column v. The function returns NULL because there are no rows.

SELECT MEDIAN(v)
  FROM aggr;
+------------+
| MEDIAN (V) |
|------------|
|       NULL |
+------------+

插入一些行:

INSERT INTO aggr VALUES (1, 10), (1, 20), (1, 21);
INSERT INTO aggr VALUES (2, 10), (2, 20), (2, 25), (2, 30);
INSERT INTO aggr VALUES (3, NULL);

Get the MEDIAN value for each group. Note that because the number of values in group k = 2 is an even number, the returned value for that group is the mid-point between the two middle numbers.

SELECT k, MEDIAN(v)
  FROM aggr
  GROUP BY k
  ORDER BY k;
+---+-----------+
| K | MEDIAN(V) |
|---+-----------|
| 1 |  20.00000 |
| 2 |  22.50000 |
| 3 |      NULL |
+---+-----------+