对于number和Date的处理只是针对于单一数据。
Student表:
聚合函数:
一列数据中的最大值——max(字段):
select max(age) from STUDENTS;//此处返回的结果就是14,max函数可应用的类型包括数值型和字符型。假若有多个最大值,则只显示一个。
select max(name) from students;//此处返回的是张四,由此可知当应用于字符型的时候,oralce会按照字母表的顺序进行排序。如果有英文名,英文名永远排在中文之前。
//应用到日期上时也是获得最晚日期。
一列数据中的最小值——min(字段):
于max函数刚好相反,但需要注意的是,如果含英文和中文,英文也总在中文前。
平均值——avg(字段):
select avg(age) from students;//返回13.25
求和——sum(字段):
select sum(age) from students;//返回106
统计记录数——count(字段):
select count(age) from students;//返回8 //若当age中有一个数据为null时,count将不会统计这一行。 //当关键字为count(*)时,即使所有字段都为null,也会统计进去。 //count(*)等同于count(1)。
常用技巧:
多值判断——decode()函数:
decode(表达式,比较值1,结果值1,比较值2,结果值2,,....,默认值)
select name,decode(sign(instr(position,'学生')),1,'屌丝','班干部') department from students; //sign是number型的处理函数,判断正负性。 instr是检索字符串的函数。 //判断字段中是否含有'学生',如果有,就是屌丝,否则就是班干部。如下图。
空值处理——nvl()函数:
nvl(表达式,新值/表达式)
select name,nvl(age,0) from students;//若有学生的age字段为空的时候,就会显示0;
结果集行号——rownum()函数:
rownum可以返回结果集的行号,select每捕捉一条记录,rownum便增加1。否则rownum保持不变。
select id,name,rownum from student;//显示结果如下图:
强制数据类型转换——cast()函数:
cast(原数据 as 新数据);
create table student1 as select cast(s.ADDRESS as varchar2 (20)) address, cast(s.AGE as varchar2 (20)) age, cast(s.NAME as varchar2 (20)) name, cast(s.POSITION as varchar2(20)) position from STUDENT s; //创建了新表student1,内容于student表一样,更改了字段类型。
Oracle中的运算:
oracle中的运算包括数学运算、逻辑运算、比较运算和按位运算。
数学运算:加(+) 减(-) 乘(*) 除(/)
select 3*4 from dual;//此处不管是哪种运算符号,或者3改成'3',number改成字符串型。结果都是于正常的运算相同。 //当其中一个操作数为null时,结果也为null。当有数据为null是,需要用nvl()函数。
逻辑运算符:
大于:> 大等于:>= 小于:< 小等于:<= 等于:= 不等于:<>或者!= 这些可以用于数值,日期和字符串的比较。 取反:NOT 布尔值的与操作:AND 布尔值的或操作:OR 需要注意的是:无论哪种逻辑运算,只要有一个操作数据为null,运算结果一定是假。包括where null=null,null<>null也为假。
特殊判式:
between——范围测试;
select * from student where age between 12 and 16; //查询年龄在12到16岁的人的信息(包含)。
in——集合成员测试;
select * from student where age in (12,14,16); //查询年龄为12,14和16岁的人的信息。
lie——模糊匹配;
select name from student where name like '张%%';//搜索出来两个:张千利,张四。 select name from student where name like '张_';//只搜索出来一个:张四。 //可见,_是单个字符的通配符,可使用多个。 select 1 result from dual where '10%' like '%\%'escape '\';//结果为1 select 1 result from dual where '10' like '%\%'escape '\';//结果为null。 //可见,escape是转义字符,将后面的%由通配符专成了百分号。
is null——空值判断;
select * from student where age is null;//当age为null时才会有结果。 select * from student where age is not null;//当age为不为null时才会有结果。
exits——是否存在判断;
select * from student where exists(select name from student where id=1 );//先判断student表里面有没有id=1的记录,如果返回1查询所有student的记录。返回0则不进行前面的查询。
all、some、any——数量判断;
查找表中所有比所有学生年龄大的所有人,就是用一部分数据(大于一个)与一部分(大于一个)作比较。
select * from student where age > all(select age from student where position = '学生' ); //等同于:就是说要查询出的人每个人都得大于比较条件中任何一个人。 select * from student where age >(select max(age) from student where position='学生'); //用any和some,则代表只要每个人大于比较条件中的随便一个人都成立。