Counting and averaging · Contagem e média
Summarising with aggregate functions
Sometimes you do not want the rows themselves, but a summary of them. Aggregate functions turn many rows into a single value:
COUNT(*)— how many rowsSUM(col)— the totalAVG(col)— the averageMIN(col)/MAX(col)— the smallest / largest
Resumindo com funções agregadas
Às vezes você não quer as próprias linhas, mas um resumo delas. Funções agregadas convertem muitas linhas em um único valor:
COUNT(*)— quantas linhasSUM(col)— o totalAVG(col)— a médiaMIN(col)/MAX(col)— o menor / o maior
SELECT COUNT(*) FROM student;
Naming and rounding the result
Give the result a clear heading with AS. Averages often have long decimals, so wrap them in ROUND(value, 2) to keep 2 decimal places:
You can combine several aggregates in one query.
Nomeando e arredondando o resultado
Dê ao resultado um título claro com AS. Médias frequentemente têm muitas casas decimais, então envolva-as em ROUND(value, 2) para manter 2 casas decimais:
SELECT COUNT(*) AS n, ROUND(AVG(score), 2) AS avg_score
FROM student;
Você pode combinar várias agregações em uma única consulta.
Common mistakes
COUNT(*)counts rows;AVG(col)averages a column.- Round an average with
ROUND(x, 2).
Erros comuns
COUNT(*)conta linhas;AVG(col)calcula a média de uma coluna.- Arredonde uma média com
ROUND(x, 2).
In one query, show how many students there are as n, and their average score (to 2 decimal places) as avg_score. · Em uma única consulta, exiba quantos alunos existem como n e sua nota média (com 2 casas decimais) como avg_score.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Show the lowest score as lowest, the highest as highest, and the total of all scores as total. · Exiba a menor nota como lowest, a maior como highest e a soma de todas as notas como total.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.