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>