Função MySQL VAR_SAMP()

Resumo : neste tutorial, você aprenderá como usar a VAR_SAMP()função MySQL para calcular a variância amostral de valores em uma coluna de uma tabela.

Introdução à função MySQL VAR_SAMP()

A VAR_SAMP()função é uma função agregada que retorna a variação amostral dos valores em uma coluna de uma tabela.

Aqui está a sintaxe da VAR_SAMP()função:

SELECT VAR_SAMP(column_name)
FROM table_name;Linguagem de código:  SQL (linguagem de consulta estruturada)  ( sql )

O VAR_SAMP()retorno NULLse os valores forem NULLou não houver linhas correspondentes.

Na prática, você usa a VAR_SAMP()função quando tem uma amostra da população, e não da população inteira.

Observe que para calcular a variação da população, você usa a função VAR_POP()ou VARIANCE().

Exemplo de função MySQL VAR_SAMP()

Primeiro, crie uma nova tabela chamada apples:

CREATE TABLE apples(
   id INT AUTO_INCREMENT,
   color VARCHAR(255) NOT NULL,
   weight DECIMAL(6,2) NOT NULL,
   PRIMARY KEY(id)
);Linguagem de código:  SQL (linguagem de consulta estruturada)  ( sql )

Segundo, insira algumas linhas na applestabela:

INSERT INTO apples (color, weight) VALUES
    ('Red', 0.6),
    ('Green', 0.4),
    ('Yellow', 0.35),
    ('Red', 0.28),
    ('Green', 0.42),
    ('Orange', 0.38),
    ('Red', 0.31),
    ('Purple', 0.45),
    ('Green', 0.37),
    ('Yellow', 0.33);Linguagem de código:  SQL (linguagem de consulta estruturada)  ( sql )

Terceiro, consulte os dados da applestabela:

SELECT * FROM apples;Linguagem de código:  SQL (linguagem de consulta estruturada)  ( sql )

Saída:

+----+--------+--------+
| id | color  | weight |
+----+--------+--------+
|  1 | Red    |   0.60 |
|  2 | Green  |   0.40 |
|  3 | Yellow |   0.35 |
|  4 | Red    |   0.28 |
|  5 | Green  |   0.42 |
|  6 | Orange |   0.38 |
|  7 | Red    |   0.31 |
|  8 | Purple |   0.45 |
|  9 | Green  |   0.37 |
| 10 | Yellow |   0.33 |
+----+--------+--------+Linguagem de código:  SQL (linguagem de consulta estruturada)  ( sql )

Finalmente, calcule a variância amostral da weighttabela apples:

SELECT color, VAR_SAMP(weight)
FROM apples
GROUP BY color;Linguagem de código:  SQL (linguagem de consulta estruturada)  ( sql )

Saída:

+--------+------------------------+
| color  | VAR_SAMP(weight)       |
+--------+------------------------+
| Red    |   0.031233333333333325 |
| Green  |  0.0006333333333333332 |
| Yellow | 0.00019999999999999868 |
| Orange |                   NULL |
| Purple |                   NULL |
+--------+------------------------+Linguagem de código:  SQL (linguagem de consulta estruturada)  ( sql )

Resumo

  • Use a VAR_SAMP()função MySQL para calcular a variação amostral de valores em uma coluna de uma tabela.

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *