SQLite AVG()
函数用于检索表达式或给定列的平均值。
语法
SELECT AVG(aggregate_expression) FROM tables [WHERE conditions];
在GROUP BY
子句中使用AVG()
函数时的语法:
SELECT expression1, expression2, ... expression_n AVG(aggregate_expression) FROM tables [WHERE conditions] GROUP BY expression1, expression2, ... expression_n;
示例1:
假设有一个名为student
的表,具有以下数据:
从student
表中检索学生的平均费用(fees
):
SELECT AVG(FEES) AS "Avg Fees" FROM STUDENT WHERE ID > 0;
执行上面查询代码,得到以下结果 -
sqlite> SELECT AVG(FEES) AS "Avg Fees" ...> FROM STUDENT ...> WHERE ID > 0; 18777.7777777778 sqlite>
示例2:
使用带有DISTINCT
子句的AVG()
函数,从student
表中获取FEES
大于10000
并且平均不同费用。
SELECT AVG(DISTINCT FEES) AS "Avg Fees" FROM STUDENT WHERE FEES > 10000;
执行上面查询代码,得到以下结果 -
sqlite> SELECT AVG(DISTINCT FEES) AS "Avg Fees" ...> FROM STUDENT ...> WHERE FEES > 10000; 28600.0 sqlite>
示例3:
使用数学公式在AVG()
函数中计算求平均值。
可以使用数学公式根据您的要求检索平均值,如下求每个月的平均值 -
SELECT AVG(FEES / 12) AS "Average Monthly Fees" FROM STUDENT;
执行上面查询代码,得到以下结果 -
sqlite> SELECT AVG(FEES / 12) AS "Average Monthly Fees" ...> FROM STUDENT; 1564.81481481481 sqlite>
示例4:
使用具有的GROUP BY
子句的AVG()
函数:
从student
表中检索NAME
和FEES
,并按AGE
分组数据:
SELECT NAME, SUM(FEES) AS "Avg Fees by Name" FROM STUDENT GROUP BY AGE;
执行上面代码,得到以下结果 -
sqlite> SELECT NAME, SUM(FEES) AS "Avg Fees by Name" ...> FROM STUDENT ...> GROUP BY AGE; Javasu|18000.0 Maxsu|16000.0 Linsu|80000.0 Sqlsu|25000.0 Linsu|30000.0 sqlite>