我生之初,尚无为;我生之后,逢此百罹。

学习笔记——oracle查询

一、单表查询

以emp表为例:

条件查询:

select * from emp where empno = 1001;

--等于查询

select * from emp where sal between 1000 and 2400;

--范围查询

select * from emp where job like '%C%';

--模糊查询

select * from emp where ename in ('SMITH','ALLEN');

--集合查询

select * from emp where ename like '%A%' and sal >=2000;

--与查询

select * from emp where ename like '%M%' or ename like '%AL%';

--或查询

select * from emp where comm is not null;

--非查询

 

 

排序查询:ASC | DESC

select * from emp order by sal desc,empno ASC;

--先按sal降序排序,如果sal相同,则按empno升序排序

 

分组查询:

select deptno,job,count(*),max(sal),min(sal) from emp group by deptno,job;

--分组比较特别,一般用于统计,select后面必须是聚合函数或者group by分组的列。

 

--如果说select empno,deptno,job,count(*),max(sal),min(sal) from emp group by deptno,job;

--这里的group by 没对empno分组,但select后面又查询empno,则会报错。

如图

 

以上查询可以组合但有一定的规律:

where →group by → having →order by 

--特别注意

--where 无法使用聚合函数   having只能使用聚合函数(列函数)

select job,avg(sal) from emp where sal>800 group by job having avg(sal)>1200 order by avg(sal);

 

常用列函数:

所有列函数皆不统计NULL

max(column)  --列最大值

min(column)  --列最小值

count(*)  --行总和

count(column)  --列不为null的行总和

count(distinct column)  --列相异值的数量,可以统计用某列分组时有多少组。

sum(column)  --列求和

avg(column)  --列平均值

stddev(column)  --列的标准偏差

variance(column)

 

 列函数可不用于分组,如

select avg(sal) from emp;

--个人认为这里表示整个表就是一组

 

 

二、子查询与集合查询

以emp表和dept表为列:

 select * from emp where deptno = (select deptno from dept where dname='SALES');

--单行子查询

select * from emp where deptno in (select deptno from dept where dname like '%C%');

--多行子查询

 select * from emp where (job,deptno) = (select job,deptno from emp where empno=7654);

--多列子查询,这里要求 where 等号左边跟右边列数一致,若右边少于左边,则error:没有足够的值,若右边多于左边,则error:值过多。

select * from emp where (job,deptno) in (select job,deptno from emp where empno>=7654);

--这里也是多行子查询,不过上面是=,表明是单行子查询,这里是in,表明是多行子查询。

 

posted @ 2022-06-29 11:14  舍旃  阅读(89)  评论(0编辑  收藏  举报
我生之初,尚无造;我生之后,逢此百忧。