查询数据
查询所有数据
select * from 表;
查询空值
select * from 表名 where 列名 is null
查询非空
select * from 表名 where 列名 is not null
范围查询
and
select * from 表名 where 列名>10 and 列名<200;
between…and…
select * from 表名 where 列名 between 10(小值) and 200(大值)
select * from 表名 where 列名 not between 10(小值) and 200(大值)
in
select * from 表名 where 列名 in (10,20);
等于10的或者等于20的
union 合并查询结果集
两个查询列数一样
也可以用于合并两个查询结果集
查询结果智能化合并重复的行,如果不想合并,在union后加all
select * from 表名 where 列名=10
union
select * from 表名 where 列名=20;
like 模糊匹配
% 任意字符 不限长度
select * from 表名 where 列名 like ‘%S’;
_ 一个任意字符 只限一个字符
select * from 表名 where 列名 like ‘_S%’;
第二位是S
练习
SQL> select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 1980/12/17 800.00 20
7499 ALLEN SALESMAN 7698 1981/2/20 1600.00 300.00 30
7521 WARD SALESMAN 7698 1981/2/22 1250.00 500.00 30
7566 JONES MANAGER 7839 1981/4/2 2975.00 20
7654 MARTIN SALESMAN 7698 1981/9/28 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 1981/5/1 2850.00 30
7782 CLARK MANAGER 7839 1981/6/9 2450.00 10
7788 SCOTT ANALYST 7566 1987/4/19 3000.00 20
7839 KING PRESIDENT 1981/11/17 5000.00 10
7844 TURNER SALESMAN 7698 1981/9/8 1500.00 0.00 30
7876 ADAMS CLERK 7788 1987/5/23 1100.00 20
7900 JAMES CLERK 7698 1981/12/3 950.00 30
7902 FORD ANALYST 7566 1981/12/3 3000.00 20
7934 MILLER CLERK 7782 1982/1/23 1300.00 10
1、查询员工姓名不带S的员工信息
select * from emp where ename not like ‘%S%’;
2、查询不在10号和20号部门的员工信息
select * from emp where deptno not in(10,20);
3、查询10号部门工资3000以上的员工信息
select * from emp where deptno=10 and sal>3000;
4、查询上司是SMITH的员工信息
select * from emp where mgr=(select empno from emp where ename=‘SMITH’);
order by排序
升序 asc
降序 desc
select * from 表名 order by 列名 asc;
select * from 表名 order by 列名 asc,列名2 desc;
最终结果先按第一个规则排序,再按照第二个规则排序
排序可以用别名
select ename,deptno as 部门 from emp order by 部门=10;
行号
select emp.*,rownum from emp order by sal;
行号还是排序之前原始的行号
查询工资最高的前三个
行号重新生成
select* from(
select mytable.*,rownum as rn别名 from
(
select * from emp order by sal desc
)mytable 临时表名
)t别名 where rn<=3;
聚合函数
对表中的某一列数据进行聚合运算得到结果
聚合运算最后只有一个结果
where后面不允许出现聚合函数
sum()
avg()
max()
min()
count()
查询10号部门的平均工资
select avg(sal) from emp where deptno=10;
count 不能写有空值的,一般写*
select count(*) from emp where deptno=10;
查询最高最低工资
select max(sal),min(sal) from emp;
计算年薪
select max((sal+nvl(comm,0))*13) from emp;
group by分组
对数据进行分类统计
按部门分组
select deptno from emp group by deptno;
每部门多少人
select deptno,count(*) from emp group by deptno;
每个部门最高工资
select deptno,max(sal) from emp group by deptno;
降序排列
select deptno,max(sal) from emp group by deptno order by max(sal) desc;
分组后可以选择的列
1、被分组的列
2、使用聚合函数统计的列
分组之后还要继续筛选用having
子句出现顺序
select…from…where…group by…having…order by…
where 条件 分组之前 不能使用聚合函数
having 条件 分组之后 可以使用聚合函数
练习
统计工资超过2000的人至少2个部门
select deptno from emp
where sal>=2000
group by deptno
having count(*)>=2
按照两列分组
select deptno,job from emp group bu deptno,job;
先后顺序不影响结果
select deptno,job,count(*) from emp group by deptno,job;
select deptno,min(dirdate)