Categorias:

Funções de agregação (General) , Funções de janela

MEDIAN

Determina a mediana de um conjunto de valores.

Sintaxe

Função de agregação

MEDIAN( <expr> )

Função de janela

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

Argumento

expr

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

Retornos

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

Notas de uso

  • Se o número de valores diferente de NULL for um número ímpar maior ou igual a 1, isto retornará o valor mediano (“centro”) dos valores diferentes de NULL.

  • Se o número de valores diferentes de NULL for um número par, isto retornará um valor igual à média dos dois valores centrais. Por exemplo, se os valores forem 1, 3, 5 e 20, então isso retornará 4 (a média de 3 e 5).

  • Se todos os valores forem NULL, isto retornará NULL.

  • Se o número de valores não NULL for 0, isto retornará NULL.

  • DISTINCT não é suportado para esta função.

  • Quando esta função é chamada como uma função de janela, ela não oferece suporte para:

    • Uma cláusula ORDER BY dentro da cláusula OVER.

    • Quadros de janela explícitos.

Exemplos

Isso mostra como usar a função.

Criar uma tabela vazia.

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 |
+------------+

Inserir algumas linhas:

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 |
+---+-----------+