SQL MAX 函數(shù)

2018-08-12 22:09 更新

SQL MAX 函數(shù)

MAX函數(shù)用于找出記錄集中具有最大值的記錄。

要理解 MAX 函數(shù),請考慮 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)在,假設你想要獲取 daily_typing_pages 的最大值,那么你可以用如下命令來達到目的:

    SQL> SELECT MAX(daily_typing_pages)
        -> FROM employee_tbl;
    +-------------------------+
    | MAX(daily_typing_pages) |
    +-------------------------+
    |                     350 |
    +-------------------------+
    1 row in set (0.00 sec)

你還可以使用 GROUP BY 子句,為每個名字(name)找出 daily_typing_pages 的最大值:

    SQL> SELECT id, name, MAX(daily_typing_pages)
        -> FROM employee_tbl GROUP BY name;
    +------+------+-------------------------+
    | id   | name | MAX(daily_typing_pages) |
    +------+------+-------------------------+
    |    3 | Jack |                     170 |
    |    4 | Jill |                     220 |
    |    1 | John |                     250 |
    |    2 | Ram  |                     220 |
    |    5 | Zara |                     350 |
    +------+------+-------------------------+
    5 rows in set (0.00 sec)

你還可以將 MIN 函數(shù)同 MAX 函數(shù)一起使用,來找出最小值。試一下下面的例子:

    SQL> SELECT MIN(daily_typing_pages) least, MAX(daily_typing_pages) max
        -> FROM employee_tbl;
    +-------+------+
    | least | max  |
    +-------+------+
    |   100 |  350 |
    +-------+------+
    1 row in set (0.01 sec)

你還可以將 MIN 函數(shù)同 MAX 函數(shù)一起使用,來找出最小值。試一下下面的例子:

    SQL> SELECT MIN(daily_typing_pages) least, 
        -> MAX(daily_typing_pages) max
        -> FROM employee_tbl;
    +-------+------+
    | least | max  |
    +-------+------+
    |   100 |  350 |
    +-------+------+
    1 row in set (0.01 sec)
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號