SQL AVG 函數(shù)

2018-08-12 22:09 更新

SQL AVG 函數(shù)

AVG函數(shù)用于找出表中記錄在某字段處的平均值。

要理解 AVG 函數(shù),請(qǐng)考慮 employee_tbl 表,表中記錄如下所示:

    SQL> SELECT * FROM employee_tbl;
    +------+------+------------+--------------------+
    | id   | name | work_date  | daily_typing_pages |
    +------+------+------------+--------------------+
    |    1 | John | 2007-01-24 |                250 |
    |    2 | Ram  | 2007-05-27 |                220 |
    |    3 | Jack | 2007-05-06 |                170 |
    |    3 | Jack | 2007-04-06 |                100 |
    |    4 | Jill | 2007-04-06 |                220 |
    |    5 | Zara | 2007-06-06 |                300 |
    |    5 | Zara | 2007-02-06 |                350 |
    +------+------+------------+--------------------+
    7 rows in set (0.00 sec)

現(xiàn)在,假設(shè)你想要獲取 daily_typing_pages 的平均值,那么你可以用如下命令來(lái)達(dá)到目的:

    SQL> SELECT AVG(daily_typing_pages)
        -> FROM employee_tbl;
    +-------------------------+
    | AVG(daily_typing_pages) |
    +-------------------------+
    |                230.0000 |
    +-------------------------+
    1 row in set (0.03 sec)

你還可以使用 GROUP BY 子句來(lái)計(jì)算不同記錄分組的平均值。下面的例子將會(huì)計(jì)算得出每個(gè)人平均值,你將能夠得到平均每個(gè)人每天打的頁(yè)數(shù)。

    SQL> SELECT name, AVG(daily_typing_pages)
        -> FROM employee_tbl GROUP BY name;
    +------+-------------------------+
    | name | AVG(daily_typing_pages) |
    +------+-------------------------+
    | Jack |                135.0000 |
    | Jill |                220.0000 |
    | John |                250.0000 |
    | Ram  |                220.0000 |
    | Zara |                325.0000 |
    +------+-------------------------+
    5 rows in set (0.20 sec)
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)