目录
数学相关的函数
1.向下整取 floor(num)
select floor(3.45); --->3
2. 四舍五入 round(num)
select round(23.8); ---->24
select round(num,m) m代表小数点后几位
3.非四舍五入 truncate(num,m)
select truncate(num,m); m代表保留几位
4.随机数 rand() 0-1 不包含1
select rand();
分组查询 group by
1.查询每个部门的平均工资
select deptno,avg(sal) from emp group by deptno;
2.查询每个部门的工资总和
select deptno,sum(sal) from emp group by deptno;
3.查询每个领导下的人数
select mgr,count(*) from emp where mgr is not null group by mgr;
4.查询每个部门工资大于1000的员工数量
select deptno, count(*) from emp where sal>1000 group by deptno;
5.每个部门每个主管的手下人数
select deptno,mgr,count(*) from emp where mgr is not null group by deptno,mgr;
having 面试容易被问道
where 前面不可以有group by。 having前面可以有 group by , 但是 having 后面不可以有group by
注意:
-
where后面只能写普通字段的条件 不能写聚合函数的条件 where sum(sal)>100
-
having和where类似都是用于添加条件的,having后面可以写普通字段的条件也可以写聚合函数的条件,但是建议写聚合函数的条件,而且要结合group by 使用 。
1.查询每个部门的平均工资,要求平均工资大于2000
select avg(sal) ag from emp group by deptno having ag>2000;
2.查询商品表中每个分类的平均单价,要求平均单 价小于100
select category_id,avg(price) ag from t_item group by category_id having ag<100;
3.查询emp表中工资在1000-3000之间的员工,每个部门的编号,工资总和,平均工资,过滤掉平均工资,低于2000的部门,按照平均工资降序排序
select deptno,sum(sal) ,avg(sal) ag from emp
where sal between 1000and 3000
group by deptno having ag>=2000
order by ag desc;
子查询(嵌套查询)
可以在查询语句中嵌套另一条sql语句,可以嵌套n层。
1.查询emp表中工资最高的员工信息
select * from emp where sal=(select max(sal) from emp);
2.查询emp表中工资大于平均工资的员工信息
select * from emp where sal>(select avg(sal) from emp);
3.查询 工资高于 20号部门最高工资的 员工信息
lect * from emp sal>(select max(sal) from emp deptno=20);
4.查询 工资最低的员工的 同事们 的信息(同事=相同job)得到最低工资
select * from emp where job=(select job from emp
where sal=( select min(sal) from emp))and sal!=(select min(sal) from emp);
子查询总结:
1.嵌套在sql语句中的查询语句称为子查询
2.子查询可以嵌套n层
3.子查询可以写在什么位置?
i 写在where和having的后面 当做查询条件的值
ii 写在创建表的时候 格式: create table 表名 as (子查询)
iii 写在from后面当成一个虚拟表 **必须有别名