SQL 平均 ()
AVG() 函數
AVG() 函數傳回數值列的平均值。
SQL AVG() 語法
SELECT AVG(column_name) FROM table_name
##示範資料庫在本教程中,我們將使用php 樣本資料庫。 下面是選自"access_log" 表的資料:
+-----+---------+------- +------------+
| aid | site_id | count | date |
+-----+---------+---- ---+------------+
| 1 | 1 | 45 | 2016-05-10 1 2001 |
| 3 | 1 | 230 | 2016-05-14 |
| 4 | 5 | 5 | 205 | 2016-05-14 |
| 6 | 4 | 13 | 2016-05-15 |
| 7 | 3 | 220 | 2016-05-15 |
| 8 | 5 | 545 | 2016-05-16 |
| 9 | 3 | 201 | 2016-05-17 |
+-----+---------+-------+----------- -+
SQL AVG() 實例+-----+---------+---- ---+------------+
| 1 | 1 | 45 | 2016-05-10 1 2001 |
| 3 | 1 | 230 | 2016-05-14 |
| 4 | 5 | 5 | 205 | 2016-05-14 |
| 6 | 4 | 13 | 2016-05-15 |
| 7 | 3 | 220 | 2016-05-15 |
| 8 | 5 | 545 | 2016-05-16 |
| 9 | 3 | 201 | 2016-05-17 |
+-----+---------+-------+----------- -+
下面的SQL 語句從"access_log" 表的"count" 欄位取得平均值:
#實例
SELECT AVG(count) AS CountAverage FROM access_log;執行上述SQL 輸出結果如下:
下面的SQL 語句選擇訪問量高於平均訪問量的"site_id" 和"count":
實例
SELECT site_id, count FROM access_log
WHERE count > (SELECT AVG(count) FROM access_log);
執行上述 SQL 輸出結果如下:
##