1、select语句
-分组函数GROUP BY 是分组查询, 一般 GROUP BY 是和聚合函数配合使用
-group by XX
eg:select avg(sal)from emp group by deptno;
-having 对分组进行限制过滤
eg: select avg(sal),deptno from emp group by deptno having avg(sal) >2000;
where 是对单条记录数据进行过滤。
eg:select avg(sal),deptno from emp group by deptno where avg(sal)>2000;//这个是错的
-注意在语句的过程的时候要按关键字进行。
练习:
select avg(sal)
from emp
where sal>1200
group by deptno
having avg(sal) >1500
order by avg(sal) desc;
2、子查询
select套如select语句
-查工资最高的人
eg: select ename,sal from emp where sal = (select max(sal) from emp);
-平均工资之上的人
eg:select ename,sal from emp where sal > (select avg(sal) from emp);//(select avg(sal) from emp)只能返回单个值
3、表连接,关键把他当成一张表,t是起的别名。
-eg:
select ename ,sal from emp
join (select max(sal)max_sal ,deptno from emp group by deptno) t
on (emp.sal = t.max_sal and emp.deptno = t.deptno);
4.自连接:为同一张表其不同的别名。在选同一张表下的相互关系。如求他的经理人。可以定义两张表,起个别名。
eg.select e1.ename,e2.ename from emp e1,empe2 where e1.mgr = e2.empno;
5.过滤条件和连接条件的新标准:
·1990的SQL标准的找法:
·1999年新SQL标准:过滤条件和连接条件分开。如下
join ---on
多张表连接加过滤
left(outer) join :左边的表的多余的、连不上右边的表的数据显示出来:同理还有right outer join
full join 左右没有连接上(多余的)的数据的显示。
综合实例: