Having的用法

来源:互联网 发布:2017淘宝游戏专营 编辑:程序博客网 时间:2024/04/30 07:09

一、实例

Examine the description of the EMPLOYEES table:EMP_ID NUMBER(4) NOT NULL LAST_NAME VARCHAR2(30) NOT NULLFIRST_NAME VARCHAR2(30)DEPT_ID NUMBER(2)JOB_CAT VARCHAR2(30)SALARY NUMBER(8,2)Which statement shows the department ID, minimum salary, and maximum salary paid in thatdepartment, only if the minimum salary is less than 5000 and maximum salary is more than 15000?
然后给的解答是:SELECT dept_id, MIN(salary), MAX(salary)FROM employeesGROUP BY dept_idHAVING MIN(salary) < 5000 AND MAX(salary) > 15000;

二、解析


group by 和having的关系就像select和where的关系。
这里,MIN(), MAX()是聚合函数,作用分别是求最大值和求最小值

MIN(), MAX()是聚合函数.group by 后面是要跟着的 select 中所有不是聚合函数的字段。ex1:  select count(*) from emp;         //只是查询总总数 emp这张表里一共有多少条记录 所以不用group byex2:  select count(*) , deptno from emp group by deptno;                      // 根据deptno 分组, 查到的数据就是  列出 不同部门 记录总数           select count(*) ,  deptno ,  comm from emp group by deptno , comm;                    // 根据deptno 和 comm 分组  以此类推                       group by 后面是要跟着的 select 中所有不是聚合函数的字段   否则会报错。having 相当于where     与where的唯一区别是 当查询语句中有 聚合函数 的时候 就不能用where 了  只能用having

1 0
原创粉丝点击