GROUP BY 語句根據一個或多個欄位將結果集分組。
在分組的欄位上我們可以使用 COUNT, SUM, AVG,等函數。
GROUP BY 語法
SELECT column_name,function(column_name)FROM table_name
WHERE column_name operator value
GROUP BY column_name;先將以下數據導入資料庫中。
-ion> 79 `employee) c ` char(10) NOT NULL DEFAULT '',
-> `date` datetime NOT NULL, -> `singin` tinyint(4) NOT NULL DEFAULT '0' id`)
-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;Query OK, 0 rows affected (0.04 sec)
MariaDB [RUNOOB]> BEGIN;Query OK, 00.005, 00500005)> > 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: 6RUatSLetRU OK, 0 rows affected (0.00 sec)
MariaDB [RUNOOB]> SET FOREIGN_KEY_CHECKS = 1;Query OK, 0 rows affected (0.00 sec)
語。 select * from employee_tbl;+----+------+---------------------+--------+
| id | name | date | singin |
+----+------+---------------------+----- ---+
| 1 | aa | 2016-04-22 15:25:33 | 1 |
| 2 | bb 04-19 15:26:02 | 2 |
| 4 | bb | 2016-04-07 15:26:14 | 5 |
| 6 | aa | 2016-04-04 15:26:54 | 2 |
+----+------+------------------ ---+--------+
6 rows in set (0.00 sec)
接下來我們使用GROUP BY 語句將資料表按名字分組,並統計每個人有多少筆記錄:
MariaDB [RUNOOB]> SELECT name, COUNT(*) FROM employee_tbl GROUP BY name;+------+----------+
| name | COUNT(*) |+- -----+----------+
| aa | 3 |
| bb | 2 |
|cc cc | 1 |
| 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-RO name WITH-RO name++ ---+--------------+
| name | singin_count |
+------+--------------+
| aa | 7 |
| bb | 7 |
| cc | +--------------+
4 rows in set (0.00 sec)
參數說明:
如果a!=nullull
參數說明:
如果a!=nullull,a;如果a==null,則選擇b;
如果b==null,則選擇c;
MariaDB [RUNOOB]> SELECT coalesce(name, '總數'), SUM(singin) as singin_count FROM employee_tbl GROUP BY name AND ROLLUP;+------------------- -----+ --------------+
| coalesce(name, '總數') | singin_count |
+-------------- ----------+------------------------+
| aa | 7 |
| bb
|抄送 | 2 |
|總數 1 --+
集合中4 行( 0.00 秒)