SQL Avg 函数

SQL Avg() 函数返回一个数字列的平均值。

SQL Avg() 函数语法

SELECT AVG(ColumnName)
FROM 数据表
WHERE predicates

SQL Avg() 函数范例

数据表: Employees

EmployeeId FirstName LastName Department Salary
203 Grrhh Huus Finance 78000
205 Yrbbg Bcciu Finance 57000
303 Aliice Benyu Development 55000
302 Yqfgge Llyqu Development 75000

例1
我们想知道所有职员的平均工资:

SELECT AVG(Salary) AS "Average salary"
FROM Employees

结果会类似于:

Average salary
66250

例2
如果我们想知道每个部门的平均工资,可以使用GROUP BY子句:

SELECT Department, AVG(Salary) AS "Average salary"
FROM Employees
GROUP BY Department

结果会类似于:

Department Average salary
Finance 67500
Development 65000

例3
如果我们想知道每个部门最高,最低和平均工资:

SELECT Department
           , MAX(Salary) AS "Highest salary"
           , MIN(Salary) AS "Lowest salary"
           , AVG(Salary) AS "Average salary"
FROM Employees
GROUP BY Department

结果会类似于:

Department Highest salary Lowest salary Average salary
Finance 78000 57000 67500
Development 75000 55000 65000