Having的用法

一、实例

Examine the description of the EMPLOYEES table:
EMP_ID NUMBER(4) NOT NULL LAST_
NAME VARCHAR2(30) NOT NULL
FIRST_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 that
department, only if the minimum salary is less than 5000 and maximum salary is more than 15000?

然后给的解答是:SELECT dept_id, MIN(salary), MAX(salary)
FROM employees
GROUP BY dept_id
HAVING 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 by
ex2:  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

你可能感兴趣的:(Having的用法)