SQLite AVG()函數

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的表,具有以下數據:

SQLite

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表中檢索NAMEFEES,並按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>