Lesson 3 Single Row Functions
函数分为:
1.单行函数: ①字符函数 ②日期函 ③数字函 ④转换函数
2.分组函数
学前须知:
哑表dual:是一个虚拟表,辅助查找和运算。通常用在select语句中,作为查询的目标表结构,oracle保证dual里面永远只有 一条记录。
例如: 显示1+1的结果,可以看出,dual很多时候是为了构成select的标准语法
select 1+1 from dual;
字符函数:
①LOWER:转换成小写
② UPPER:转换成大写
③ INITCAP:首字母变成大写,其余都小写
④ CONCAT:字符串的连接
⑤ SUBSTR(str,start,length):字符串的截取
⑥ LENGTH:求字符串的长度
⑦ NVL : 转换null的值。
LOWER 把字符转为小写
例如:把'HELLO'转换为小写
select lower('HELLO') from dual;
例如:把s_emp表中的last_name列的值转换为小写
select lower(last_name) from s_emp;
upper 把字符转换为大写
例如:把'world'转换为大写
select upper('world') from dual;
例如:把s_emp表中的last_name列的值转换为大写
select upper(last_name) from s_emp;
例如:查询s_emp表中名字为Ngao的人信息
这样是查不到:
select last_name,salary,dept_id
from s_emp
where last_name='NGAO';
这样就可以查询到了:
select last_name,salary,dept_id
from s_emp
where upper(last_name)='NGAO';
initcap 把字符串首字母大写
例如:把'hELLO'转换为首字母大写,其余字母小写
select initcap('hELLO') from dual;
concat 把俩个字符串连接在一起(类似之前的||的作用)
例如:把'hello'和'world'俩个字符串连接到一起,并且起个别名为msg
select concat('hello','world') msg from dual;
例如:把first_name和last_name俩个列的值连接到一起
select concat(first_name,last_name) from s_emp;
substr 截取字符串
例如:截取'hello'字符串,从第2个字符开始,截取后面的3个字符
select substr('hello',2,3) from dual;
length 获得字符串长度
例如:获得'world'字符串的长度
select length('world') from dual;
例如:获得s_emp表中last_name列的每个值的字符长度
select length(last_name) from s_emp;
nvl 替换列中为null的值
select id,last_name,nvl(commission_pct,0) commission_pct from s_emp;
1.查找last_name全小写的值为velasquez的员工的last_name
select last_name
from s_emp
where lower(last_name) = 'velasquez';
2.查找last_name的长度>10的所有员工的last_name
select last_name
from s_emp
where length(last_name)>10;
数字函数
① ROUND:四舍五入
② TRUNC:截取,不进行四舍五入
③ MOD:取余
round 四舍五入
round(arg1,arg2)
第一个参数arg1表示要进行四舍五入操作的数字
第二个参数arg2表示保留到哪一位(负数代表小数点之前,0,正数代表小数点之后)
例如: 保留到小数点后面2位
select round(45.923,2) from dual;
保留到个位 (个十百千万...)
select round(45.923,0) from dual;
保留到十位 (个十百千万...)
select round(45.923,-1) from dual;
trunc 截取到某一位
trunc(arg1,arg2) 和round的用法一样,但是trunc只舍去不进位
例如: 截取到小数点后面2位
select trunc(45.923,2) from dual;
截取到个位 (个十百千万...)
select trunc(45.923,0) from dual;
截取到十位 (个十百千万...)
select trunc(45.923,-1) from dual;