MySQL GROUP BY statement

The GROUP BY statement groups the result set based on one or more columns.

On the grouped column we can use COUNT, SUM, AVG, etc. functions.

GROUP BY syntax

SELECT column_name,function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

Example demonstration

The example in this chapter uses the following table structure and data. Before using it, we can import the following data into the database.

MariaDB [RUNOOB]> SET NAMES utf8;
Query OK, 0 rows affected (0.00 sec)

MariaDB [RUNOOB]> SET FOREIGN_KEY_CHECKS = 0;
Query OK, 0 rows affected (0.00 sec)

MariaDB [RUNOOB]> DROP TABLE IF EXISTS `employee_tbl`;
Query OK, 0 rows affected, 1 warning (0.00 sec)

MariaDB [RUNOOB]> CREATE TABLE `employee_tbl` (
    ->   `id` int(11) NOT NULL,
    ->   `name` char(10) NOT NULL DEFAULT '',
    ->   `date` datetime NOT NULL,
    -> `singin` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Number of logins',
    ->   PRIMARY KEY (`id`)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.04 sec)

MariaDB [RUNOOB]> BEGIN;
Query OK, 0 rows affected (0.00 sec)

MariaDB [RUNOOB]> INSERT INTO employee_tbl VALUES ('1', 'aa', '2016-04-22 15:25:33', '1'), ('2', 'bb', '2016-04-20 15:25:47', '3'), ('3', 'cc', '2016-04-19 15:26:02', '2'), ('4', 'bb', '2016-04-07 15:26:14', '4'), ('5', 'aa', '2016-04-11 15:26:40', '4'), ('6', 'aa', '2016-04-04 15:26:54', '2');
Query OK, 6 rows affected, 6 warnings (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 6

MariaDB [RUNOOB]> COMMIT;
Query OK, 0 rows affected (0.00 sec)

MariaDB [RUNOOB]> SET FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)

After the import is successful, execute the following SQL statement:

MariaDB [RUNOOB]> select * from employee_tbl;
+----+------+---------------------+--------+
| id | name | date                | singin |
+----+------+---------------------+--------+
|  1 | aa   | 2016-04-22 15:25:33 |      1 |
| 2 | bb | 2016-04-20 15:25:47 | 3 |
|  3 | cc   | 2016-04-19 15:26:02 |      2 |
| 4 | bb | 2016-04-07 15:26:14 | 4 |
|  5 | aa   | 2016-04-11 15:26:40 |      4 |
|  6 | aa   | 2016-04-04 15:26:54 |      2 |
+----+------+---------------------+--------+
6 rows in set (0.00 sec)

Next we use the GROUP BY statement to group the data table by name and count how many records each person has:

MariaDB [RUNOOB]> SELECT name, COUNT(*) FROM   employee_tbl GROUP BY name;
+------+----------+
| name | COUNT(*) |
+------+----------+
| aa   |        3 |
| bb   |        2 |
| cc   |        1 |
+------+----------+
3 rows in set (0.00 sec)

使用 WITH ROLLUP

WITH ROLLUP 可以实现在分组统计数据基础上再进行相同的统计(SUM,AVG,COUNT…)。

例如我们将以上的数据表按名字进行分组,再统计每个人登录的次数:

MariaDB [RUNOOB]> SELECT name, SUM(singin) as singin_count FROM  employee_tbl GROUP BY name WITH ROLLUP;
+------+--------------+
| name | singin_count |
+------+--------------+
| aa   |            7 |
| bb   |            7 |
| cc   |            2 |
| NULL |           16 |
+------+--------------+
4 rows in set (0.00 sec)

其中记录 NULL 表示所有人的登录次数。

我们可以使用 coalesce 来设置一个可以取代 NUll 的名称,coalesce 语法:

select coalesce(a,b,c);

参数说明:

如果a!=null,则选择a;

如果a==null,则选择b;

如果b==null,则选择c;

如果a b c 都为null ,则返回为null(没意义)。

以下实例中如果名字为空我们使用总数代替:

MariaDB [RUNOOB]> SELECT coalesce(name, '总数'), SUM(singin) as singin_count FROM  employee_tbl GROUP BY name WITH ROLLUP;
+------------------------+--------------+
| coalesce(name, '总数')     | singin_count |
+------------------------+--------------+
| aa                     |            7 |
| bb                     |            7 |
| cc                     |            2 |
| 总数                    |           16 |
+------------------------+--------------+
4 rows in set (0.00 sec)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326474842&siteId=291194637