概述
- 在
MySQL
中,分组和分组筛选是使用GROUP BY
和HAVING
子句来实现的 GROUP BY
用于将查询结果按一列或多列分组HAVING
用于在分组后的结果中进一步筛选
group by
- 按部门分组并计算每个部门的平均薪水
1 2 3 |
SELECT dept_id, AVG(salary) AS avg_salary FROM employees GROUP BY dept_id; |
having
-
规则:
having
必须和group by
一起结合使用
-
按部门分组并筛选出平均薪水大于5500的部门
1 2 3 4 |
SELECT dept_id, AVG(salary) AS avg_salary FROM employees GROUP BY dept_id HAVING avg_salary > 5500; |
- 按客户分组并计算总订单金额,筛选总订单金额大于200的客户
1 2 3 4 |
SELECT customer_id, SUM(amount) AS total_amount FROM orders GROUP BY customer_id HAVING total_amount > 200; |
having
和where
WHERE
子句用于在分组和聚合之前过滤记录。它不能包含聚合函数where
用在group by
之前
HAVING
子句用于在分组和聚合之后过滤记录。它可以包含聚合函数having
用在group by
之后
1 2 3 4 5 |
SELECT product_id, SUM(amount) AS total_amount FROM sales WHERE amount >= 150 GROUP BY product_id HAVING total_amount > 200; |
本文为原创文章,版权归Aet所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ union && limit10/26
- ♥ 表操作_条件查询-运算符10/23
- ♥ 数据处理函数:单行处理函数10/24
- ♥ 数据处理函数:多行处理函数10/24
- ♥ 表_修改表结构10/26
- ♥ 表操作_数据排序10/23