功能介绍
group by: 对数据进行分组和聚合操作(可以操作单字段和多字段)
having:过滤group by的结果,也就是在分组后添加筛选条件
基础语法
select 字段列表 from 表名 [ where 条件 ] group by 分组字段名 [ having ];
where 和 having的区别
执行时机不同:where是分组之前进行过滤,不满足where条件,不参与分组;而having是分组
之后对结果进行过滤。(执行顺序:where -> 聚合函数 ->having)
判断条件不同:where不能对聚合函数进行判断,而having可以。
实践操作
1. 查询每个性别(男、女)的用户数量:
SELECT gender, COUNT(*) as count
FROM User
GROUP BY gender;
2. 查询年龄大于20的男性用户数量:
SELECT gender, COUNT(*) as count
FROM User
WHERE age > 20 AND gender = 1
GROUP BY gender;
3. 查询每个性别的用户年龄总和,并按照总和降序排序
SELECT gender, SUM(age) as total_age
FROM User
GROUP BY gender
ORDER BY total_age DESC;
4. 查询每个性别的用户数量,并筛选出数量大于等于2的分组
SELECT gender, COUNT(*) as count
FROM User
GROUP BY gender
HAVING count >= 2;
5. 查询每个性别的用户数量,并按照数量降序排序,只返回前1个分组:
SELECT gender, COUNT(*) as count
FROM User
GROUP BY gender
ORDER BY count DESC
LIMIT 1;
6.多字段分组
SELECT gender, age, COUNT(*) as count
FROM User
GROUP BY gender, age;
上一篇:MySQL - SQL聚合函数(查询操作 二)
下一篇:MySQL - order by排序查询 (查询操作 四)