SQL 分組依據
SQL GROUP BY 語句
GROUP BY 語句可結合一些聚合函數來使用
GROUP BY 語句
GROUP BY 語句用於結合聚合函數,根據一個或多個欄位將結果集分組。
SQL GROUP BY 語法
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
#示範資料庫
在本教學中,我們將使用php 樣本資料庫。
下面是選自"Websites" 表的資料:
+----+--------------+--- ------------------------+-------+---------+| id | name | url | alexa | country |
+----+----------+------------------------------------ --------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA | 1 |
| 2 | 淘寶 | https://www.taobao.com/ | 13 | CN cn/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 201 https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---------------+----------- ------------------+-------+---------+
#
GROUP BY 簡單應用程式統計access_log 各個site_id 的存取量:
##SQL GROUP BY多表連接
| 1 | Google | https://www.google.cm/ | 1 | USA | 1 |
| 2 | 淘寶 | https://www.taobao.com/ | 13 | CN cn/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 201 https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---------------+----------- ------------------+-------+---------+
#
以下是"access_log" 網站存取記錄表的資料:
mysql> SELECT * FROM access_log;
+-----+--------- +-------+------------+
| aid | site_id | count | date |
+-----+------ ---+-------+------------+
| 1 | 1 | 45 | 2016-05-10 |#1 | 2016-05-13 |
| 3 | 1 | 230 | 2016-05-14 |
| 4 | 2 | 10 | 2016-05-14 |
| 5 | 5 | 205 | 2016 -05-14 |
| 6 | 4 | 13 | 2016-05-15 |
| -15 |
| 8 | 5 | 545 | 2016-05 -16 |
| 9 | 3 | 201 | 2016-05-17 |
+-----+---------+-------+----- ---------+
9 rows in set (0.00 sec)
+-----+--------- +-------+------------+
| aid | site_id | count | date |
+-----+------ ---+-------+------------+
| 1 | 1 | 45 | 2016-05-10 |#1 | 2016-05-13 |
| 3 | 1 | 230 | 2016-05-14 |
| 4 | 2 | 10 | 2016-05-14 |
| 5 | 5 | 205 | 2016 -05-14 |
| 6 | 4 | 13 | 2016-05-15 |
| -15 |
| 8 | 5 | 545 | 2016-05 -16 |
| 9 | 3 | 201 | 2016-05-17 |
+-----+---------+-------+----- ---------+
9 rows in set (0.00 sec)
GROUP BY 簡單應用程式統計access_log 各個site_id 的存取量:
實例
SELECT site_id, SUM(access_log.count) AS
nums
FROM access_log GROUP BY site_id;
執行上述SQL 輸出結果如下:##SQL GROUP BY多表連接
現在我們想要找出每個送貨員配送的訂單數目。
下面的 SQL 語句統計所有網站的存取的記錄數:
實例SELECT Websites.name,COUNT(access_log.aid) AS nums FROM access_log
LEFT JOIN WebsitesON access_log.site_id=Websites.id
GROUP BY Websites.name;
執行上述 SQL 輸出結果如下:
GROUP BY Websites.name;
執行上述 SQL 輸出結果如下: