MySQL-GROUP BY
时间:2020-02-23 14:41:01 来源:igfitidea点击:
在本教程中,我们将学习MySQL中的GROUP BY。
GROUP BY语句
顾名思义,我们使用GROUP BY语句根据列对结果进行分组。
我们将其与汇总函数(例如SUM,COUNT等)一起使用。
GROUP BY语法
SELECT column_name FROM table_name WHERE condition GROUP BY column_name;
订单表
在本教程中,我们将使用以下"订单"表。
mysql> SELECT * FROM orders; +---------+------------+--------+-------------+---------------------+---------------------+ | orderid | employeeid | amount | orderstatus | lastmodified | created | +---------+------------+--------+-------------+---------------------+---------------------+ | 1 | e03 | 15.00 | OPEN | 2016-01-02 03:04:05 | 2016-01-02 03:04:05 | | 2 | e01 | 25.50 | OPEN | 2016-01-04 03:04:03 | 2016-01-04 03:04:03 | | 3 | e05 | 100.70 | CLOSED | 2016-02-02 03:03:04 | 2016-02-02 03:03:04 | | 4 | e02 | 22.18 | OPEN | 2016-01-02 03:04:05 | 2016-01-02 03:04:05 | | 5 | e04 | 9.50 | CANCELLED | 2016-01-04 03:04:03 | 2016-01-04 03:04:03 | | 6 | e04 | 99.99 | OPEN | 2016-02-02 03:03:04 | 2016-02-02 03:03:04 | +---------+------------+--------+-------------+---------------------+---------------------+ 6 rows in set (0.00 sec)
例子1
在下面的示例中,我们将找到每个员工下的订单总数。
为了解决这个问题,我们将结果按" employeeid"分组。
我们还将使用COUNT函数来查找订单总数。
mysql> SELECT employeeid, COUNT(orderid) AS total_order FROM orders GROUP BY employeeid; +------------+-------------+ | employeeid | total_order | +------------+-------------+ | e01 | 1 | | e02 | 1 | | e03 | 1 | | e04 | 2 | | e05 | 1 | +------------+-------------+ 5 rows in set (0.00 sec)
因此,在上面的输出中,我们可以看到employeeid'e04'下了2个订单,而所有其他员工都下了一个订单。
例子2
在以下示例中,我们将显示每个员工的OPEN订单总数。
为了解决这个问题,我们将使用WHERE子句检查orderstatus
。
然后,我们将结果按" employeeid"分组。
为了找到订单总数,我们将使用COUNT函数。
mysql> SELECT employeeid, COUNT(orderid) AS total_open_order FROM orders WHERE orderstatus = 'OPEN' GROUP BY employeeid; +------------+------------------+ | employeeid | total_open_order | +------------+------------------+ | e01 | 1 | | e02 | 1 | | e03 | 1 | | e04 | 1 | +------------+------------------+ 4 rows in set (0.00 sec)
对于上面的输出,我们可以知道每个员工都有1个OPEN订单。
例子3
在以下示例中,我们将基于订单状态显示订单总数。
为了解决这个问题,我们将结果按" orderstatus"列分组。
mysql> SELECT orderstatus, COUNT(orderid) AS total_order FROM orders GROUP BY orderstatus; +-------------+-------------+ | orderstatus | total_order | +-------------+-------------+ | OPEN | 4 | | CLOSED | 1 | | CANCELLED | 1 | +-------------+-------------+ 3 rows in set (0.00 sec)
从给定的输出中,我们可以知道有4个OPEN订单,1个CLOSED和1个CANCELED订单。