05 分组查询 GROUP BY
本篇为大家介绍分组查询。在数据仓库的实际使用中,我们常常会遇到要进行分组查询的情况,那么分组查询的含义是什么?分组查询又有哪些作用呢?
分组查询,是在条件语句中使用一个或多个字段进行查询。通过这种方式,可以将表中的数据分成不同的组,在条件语句中指定这些分组。可以进行比较、排序、筛选等操作。
如果你熟悉 SQL语言,那么应该可以很容易地看到分组查询是一种非常常见的数据表结构。SQL语言提供了许多分组查询的语法和工具,例如: 当你在一张表中需要对多个数据进行筛选时,分组查询是一个非常好的选择。
语 法
SELECT 列名列表 FROM 表名
[WHERE 条件]
GROUP BY 分组列名
[HAVING 分组后的过滤条件];
where与having的区别:
- where是gourp by分组之前的筛选条件,不满足where条件的不参与group by分组;having是group by分组之后的筛选。执行顺序:where>group by>having.
- where中不能使用聚合函数,having中可以。
举个栗子(MySQL)
数据库:world,表:city。需要回答以下问题:
- 根据countrycode分组,统计各countrycode的city数量
- 根据countrycode分组,统计各countrycode的平均population
- 查询population>1000000的city,并根据countrycode分组,获取city数量>=10的countrycode
use world;
show tables;
desc city;
-- 1. 根据countrycode分组,统计各countrycode的city数量
select countrycode, count(id) as city_cnt from city group by countrycode;
-- 2. 根据countrycode分组,统计各countrycode的平均population
select countrycode, avg(population) as population_avg from city group by countrycode;
-- 3. 查询population>1000000的city,并根据countrycode分组,获取city数量>=10的countrycode
select
countrycode
, count(id) as city_cnt -- city数量
, min(population) as population_min -- 最小population
from city
where population > 1000000 -- 筛选population>10的city
group by countrycode -- 以country分组
having city_cnt >= 10; -- 分组后筛选city数量>10的countrycode
如果不执行having语句的话,输出的结果包含了city数量<=10的countrycode:
![](https://i-blog.csdnimg.cn/blog_migrate/5d189cb60052d11604aba5be4ec06326.png)
执行having语句以后,输出的结果筛掉了city数量<=10的countrycode:
![](https://i-blog.csdnimg.cn/blog_migrate/ea1998dcef5e07b21078cd57d5ea9ab2.png)
不总结=白学
THE END