MySQL聚合统计

【数据库】MySQL聚合统计

王笃笃-CSDN博客https://blog.csdn.net/wangduduniubi?type=blog显示平均工资低于2000的部门和它的平均工资

mysql> select deptno,avg(sal) deptavg from emp group by deptno;

+--------+-------------+

| deptno | deptavg |

+--------+-------------+

| 20 | 2175.000000 |

| 30 | 1566.666667 |

| 10 | 2916.666667 |

+--------+-------------+

3 rows in set (0.01 sec)

mysql> select deptno,avg(sal) deptavg from emp group by deptno havingdeptavg<2000;

+--------+-------------+

| deptno | deptavg |

+--------+-------------+

| 30 | 1566.666667 |

+--------+-------------+

having对聚合后的数据进行条件筛选。

having 和 where 的区别

条件筛选的阶段不同

mysql> select deptno,job,avg(sal) myavg from emp where ename != 'SMITH' group by deptno,job having myavg<2000;

+--------+----------+-------------+

| deptno | job | myavg |

+--------+----------+-------------+

| 30 | SALESMAN | 1400.000000 |

| 20 | CLERK | 1100.000000 |

| 30 | CLERK | 950.000000 |

| 10 | CLERK | 1300.000000 |

+--------+----------+-------------+

where

对具体的任意列进行条件筛选

having

对分组聚合之后的结果进行条件筛选。

条件筛选的阶段不同

1

from emp

2

where ename != 'SMITH'

3

group by deptno,job

4

deptno,job,avg(sal) myavg

5

having myavg<2000;

中间筛选出来的和最终结果------>全部可以看做是逻辑上的表-->mysql 中一切皆表

相关推荐
jiayou6412 小时前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
于眠牧北13 小时前
MySQL的锁类型,表锁,行锁,MVCC中所使用的临键锁
mysql
李广坤1 天前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
Turnip12022 天前
深度解析:为什么简单的数据库"写操作"会在 MySQL 中卡住?
后端·mysql
爱可生开源社区2 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1773 天前
《从零搭建NestJS项目》
数据库·typescript
加号33 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏3 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐3 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
百锦再3 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip