1.排序(升序,降序)
语法格式:
select 字段值1,字段值2... from 表名 order by 字段值; 复制代码
1.1 按照工资升序,找出员工名和薪资
select ename,sal from emp order by sal; (这个为默认,默认升序)
注意:默认是升序。怎么指定升序或者降序?asc表示升序,desc表示降序。
select ename,sal from emp order by sal; (默认升序)
select ename,sal from emp order by sal asc;
select ename,sal from emp order by sal desc;
1.2按照工资的降序排列,当工资相同的时候在按照名字的升序排列。
select ename,sal from emp order by sal desc,ename asc;
注意: 越靠前的字段越能起主导作用。只有当前面的字段无法完成排序的时候,才会启用后面的字段。
练手:
select ename,sal from emp order by 1;
select ename,sal from emp order by 2;
select * from emp order by 6;
1.3找出工作岗位是 SALESMAN 员工,并且要求按照薪资的降序排序
select ename,job,sal from emp where job = 'SALESMAN' order by sal desc; 复制代码
执行顺序 : 先执行from,在执行where,在执行select,最后在执行order by 。
select * 3 from tablename 1 where 条件 2 order by ... 4 复制代码
order by 是最后执行的。
2.分组函数
2.1分组函数/聚合函数/多行处理函数
- count 计数
- sum 求和
- avg 平均数
- max 最大值
- min 最小值
记住: 所有的分组函数都是对“某一组”数据进行操作的。
2.2找出工资的总和?
select sum(sal) from emp;
2.3找出最高工资
select max(sal) from emp;
2.4找出最低工资
select min(sal) from emp;
2.5找出平均工资
select avg(sal) from emp;
2.6找出总人数
select count(*) from emp;
select count(ename) from emp;
分组函数一共有5个。分组函数还有另一个名字:多行处理函数。 多行处理函数的特点:输入多行,最终输出的结果是 1 行。
2.7分组函数自动忽略NULL。
select count(comm) from emp;
select sun(comm) from emp;
多此一举:不需要添加这个额外的过滤条件,分组函数自动忽略null
select sum(comm) from emp where comm is not null;
2.8找出工资高于平均工资的员工
第一步 : 找出平均工资
select avg(sal) from emp;
第二步 : 找出工资高于平均工资的员工
select ename,sal from emp where sal > (select avg(sal) from emp);
以下的错误信息:无效的使用了分组函数。
以上的错误原因:**SQL语句当中有一个语法规则,分组函数不可以直接使用在where子句当中。
因为group by 是在 where 执行之后才会执行的。
select 5 ... from 1 ... where 2 ... group by 3 ... having 4 ... order by 6 ... 复制代码
3.count(*) 和 count(具体某个字段) , 他们有什么区别?
- count(*) : 不是统计某个字段中数据的个数,而是统计总记录条数。(和某个字段无关)
- count(comm) : 表示统计comm字段中不为NULL的数据总数量。
select count(*) from emp;
select count(comm) from emp;
select count(job) from emp;
4.分组函数也可以组合起来用
select count(*),sum(sal),avg(sal),max(sal),min(sal) from emp;




















