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;
演示数据库
在本教程中,我们将使用 yssmx 样本数据库。
下面是选自 "Websites" 表的数据:
+----+--------------+---------------------------+-------+---------+ | id_name _url _alexa_country | +----+--------------+---------------------------+-------+---------+ | 1 _Google _https://www.google.cm/ _1 _USA | | 2 _淘宝 _https://www.taobao.com/ _13 _CN | | 3 _云搜索MX教程 _/ _4689 _CN | | 4 _微博 _http://weibo.com/ _20 _CN | | 5 _Facebook _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 | | 2_ 3_ 100_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 | | 7_ 3_ 220_2016-05-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;
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 Websites
ON access_log.site_id=Websites.id
GROUP BY Websites.name;
LEFT JOIN Websites
ON access_log.site_id=Websites.id
GROUP BY Websites.name;
执行以上 SQL 输出结果如下: