OCP课程5:SQL之使用单行函数

根据函数每次处理的对象是一行还是多行,分为单行函数和多行函数,如果每次处理一行,是单行函数,如果每次处理是多行,就是多行函数,本章主要讲单行函数,包括字符函数,数字函数及日期函数等。

 

 

1、字符函数

字符函数分两类:

  • 大小写转换的函数
  • 对字符操作的函数

 

 

(1)大小写转换的函数

OCP课程5:SQL之使用单行函数_第1张图片

例子:查询名字为Higgins的人员信息

SQL> select employee_id,last_name,department_id from employees where last_name='higgins';

no rows selected

由于单引号内是区分大小写的,故与Higgins不匹配,没有结果。

使用lower函数进行转换就可以匹配了。

SQL> select employee_id,last_name,department_id from employees where lower(last_name)='higgins';

EMPLOYEE_ID LAST_NAME                 DEPARTMENT_ID

----------- ------------------------- -------------

        205 Higgins                             110

 

 

(2)对字符操作的函数

OCP课程5:SQL之使用单行函数_第2张图片

 

例子:从人员表中查找工作编号第4个字母到最后为REP的人员,将他们的姓名显示在一列中,还要显示名字的长度以及名字中字母a的位置

SQL> select employee_id,concat(first_name,last_name) name,job_id,length(last_name),instr(last_name,'a') "Contains 'a'?" from employees where substr(job_id,4)='REP';

EMPLOYEE_ID NAME                                          JOB_ID     LENGTH(LAST_NAME) Contains 'a'?

----------- --------------------------------------------- ---------- ----------------- -------------

        202 PatFay                                        MK_REP                     3             2

 

 

2、数字函数

OCP课程5:SQL之使用单行函数_第3张图片

 

例子:使用round函数,四舍五入

SQL> select round(45.923,2),round(45.923,0),round(45.923,-1) from dual;

ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)

--------------- --------------- ----------------

          45.92              46               50

这里引入了一个dual表,他是一个单行单列的虚拟表,基本上oracle引入dual为的就是符合语法,主要用来选择系统变量或求一个表达式的值。

 

例子:使用trunc函数,去掉指定的位数

SQL> select trunc(45.923,2),trunc(45.923),trunc(45.923,-1) from dual;

TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-1)

--------------- ------------- ----------------

          45.92            45               40

 

例子:使用mod函数,求模

SQL> select last_name,salary,mod(salary,5000) from employees where job_id='SA_REP';

LAST_NAME                     SALARY MOD(SALARY,5000)

------------------------- ---------- ----------------

Tucker                         10000                0

 

 

3、日期函数

Oracle数据库默认存储世纪、年月日、时分秒,默认的日期格式是DD-MON-RR,RR表示的是世纪年,可以在21世纪存储20世纪的日期,在20世纪存储21世纪的日期。

 

 

(1)服务器时间sysdate

例子:取服务器时间

SQL> select sysdate from dual;

SYSDATE

------------

21-OCT-15

这里看到取出来的服务器时间只有日期,没有时间,需要修改一下参数

SQL> alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';

Session altered.

SQL> select sysdate from dual;

SYSDATE

-------------------

2015-10-21 22:44:16

 

 

(2)日期的算术运算

  • 一个日期增加一个数字或者减去一个数字,结果为一个日期
  • 两个日期相减结果为之间的天数
  • 通过除以24的方式为一天加上小时,如果是分钟,就再除以60

 

例子:查询员工至今入职多少周

SQL> select last_name,(sysdate-hire_date)/7 as weeks from employees where department_id=90;

LAST_NAME                      WEEKS

------------------------- ----------

King                      644.278679

 

 

(3)日期函数

OCP课程5:SQL之使用单行函数_第4张图片

OCP课程5:SQL之使用单行函数_第5张图片

 

例子:查看下一个星期天是几号

SQL> select next_day(sysdate,1) from dual;

NEXT_DAY(SYS

------------

25-OCT-15

SQL> select next_day(sysdate,'sunday') from dual;

NEXT_DAY(SYS

------------

25-OCT-15

假定sysdate='25-JUL-03'

OCP课程5:SQL之使用单行函数_第6张图片

 

例子:对15号这一天使用round函数

SQL> select round(to_date('2014-04-15 23:59:59','yyyy-mm-dd hh24:mi:ss'),'month') from dual;

ROUND(TO_DAT

------------

01-APR-14

 

 

4、转换函数

数据类型转换有2种:

  • 隐式转换
  • 显示转换

隐式转换可以是从字符转换成数字或者日期,也可以从数字或者日期转换成字符。

OCP课程5:SQL之使用单行函数_第7张图片

显示转换使用to_char函数将数字或者日期转换成字符,使用to_number函数将字符转换成数字,使用to_date函数将字符转换成日期。

OCP课程5:SQL之使用单行函数_第8张图片

 

 

(1)使用to_char函数将日期转换成字符

clipboard[8]

格式串规则:

  • 格式串需要使用单引号引起来
  • 格式串大小写敏感
  • 可以使用任何有效的日期格式元素
  • 可以使用fm消除前面的空格和前导0
  • 格式串和前面的日期用逗号分割

日期元素格式:

OCP课程5:SQL之使用单行函数_第9张图片

时间元素格式:

clipboard[10]

可以使用带双引号的字符串

clipboard[11]

拼写成序数

clipboard[12]

 

例子:将员工的入职时间格式化显示

SQL> select last_name,to_char(hire_date,'fmDD Month YYYY') as hiredate from employees;

LAST_NAME                 HIREDATE

------------------------- ---------------------

OConnell                  21 June 2007

Mavris                    7 June 2002

 

 

(2)使用to_char函数将数字转换成字符

clipboard[13]

数字格式元素:

OCP课程5:SQL之使用单行函数_第10张图片

 

例子:将薪水转换成字符显示,单位是美元

SQL> select to_char(salary,'$99,999.00') salary from employees where last_name='Ernst';

SALARY

-----------

  $6,000.00

 

例子:将薪水转换成字符显示,单位是 ¥,这里和客户端的操作系统的语言有关,我们Linux的语言是英文,我们Windows的中文,要显示中文的货币符号,我们使用Windows的cmd连接过来

C:\Users\shilei>sqlplus hr/[email protected]:1521/stone

SQL> select to_char(salary,'L99,999.00') from employees where employee_id=100;

TO_CHAR(SALARY,'L99,

--------------------

         ¥24,000.00

 

 

(3)字符转换成数字和日期

clipboard[15]

clipboard[16]

 

例子:将16进制'1e'转换成10进制

SQL> select to_number('1e','xx') from dual;

TO_NUMBER('1E','XX')

--------------------

                  30

 

例子:将字符串转换成日期,即使这个字符串中间有空格也可以

SQL> select to_date('2014- 04-27','yyyy-mm-dd') from dual;

TO_DATE('201

------------

27-APR-14

如果格式串前面加上fx,表示精确匹配位数,有空格就不能进行转换了

SQL> select to_date('2014- 04-27','fxyyyy-mm-dd') from dual;

select to_date('2014- 04-27','fxyyyy-mm-dd') from dual

               *

ERROR at line 1:

ORA-01858: a non-numeric character was found where a numeric was expected

去掉空格就可以了

SQL> select to_date('2014-04-27','fxyyyy-mm-dd') from dual;

TO_DATE('201

------------

27-APR-14

 

 

5、RR日期格式

使用RR日期格式就是使用两位数字来表示世纪年,可以在21世纪存储20世纪的日期,在20世纪存储21世纪的日期。

OCP课程5:SQL之使用单行函数_第11张图片

OCP课程5:SQL之使用单行函数_第12张图片

 

例子:使用RR格式,获取入职时间小于2006年的人员

SQL> select last_name,to_char(hire_date,'DD-Mon-YYYY') from employees where hire_date

LAST_NAME                 TO_CHAR(HIRE_D


------------------------- --------------

Whalen                    17-Sep-2003

 

例子:对比yy和rr格式

SQL> select to_char(to_date('27-apr-88','dd-mon-yy'),'yyyy-mm-dd') from dual;

TO_CHAR(TO

----------

2088-04-27

SQL> select to_char(to_date('27-apr-88','dd-mon-rr'),'yyyy-mm-dd') from dual;

TO_CHAR(TO

----------

1988-04-27

 

 

6、嵌套函数

单行函数可以嵌套层数不限,从最里面的函数计算起。

例子:取名字前8个字符并与'_US'拼接,大写显示

SQL> select last_name,upper(concat(substr(last_name,1,8),'_US')) from employees where department_id=60;

LAST_NAME                 UPPER(CONCAT(SUBSTR

------------------------- -------------------

Hunold                    HUNOLD_US

 

 

7、处理null的函数

  • NVL (expr1, expr2):如果第一个参数为空那么显示第二个参数的值,如果第一个参数的值不为空,则显示第一个参数本来的值。
  • NVL2 (expr1, expr2, expr3):如果第一个参数为空那么显示第三个参数的值,如果第一个参数的值不为空,则显示第二个参数的值。
  • NULLIF (expr1, expr2):如果exp1和exp2相等则返回空(NULL),否则返回第一个值。
  • COALESCE (expr1, expr2, ..., exprn):如果第一个参数为空,则看第二个参数是否是空,不为空则显示第二个参数,如果第二个参数是空再看第三个参数是否为空,不为空则显示第三个参数,依次类推。

以上函数参数的数据类型必须匹配

 

例子:使用nvl函数将提成为空的转换成提成为0

SQL> select last_name,salary,nvl(commission_pct,0),(salary*12)+(salary*12*nvl(commission_pct,0)) as sal from employees;

LAST_NAME                     SALARY NVL(COMMISSION_PCT,0)        SAL

------------------------- ---------- --------------------- ----------

OConnell                        2600                     0      31200

 

例子:使用nvl2函数,如果提成为null,显示SAL,如果提成不为null,则显示SAL+COMM

SQL> select last_name,salary,commission_pct,nvl2(commission_pct,'SAL+COMM','SAL') income from employees where department_id in (50,80);

LAST_NAME                     SALARY COMMISSION_PCT INCOME

------------------------- ---------- -------------- --------

Vargas                          2500                SAL

Russell                        14000             .4 SAL+COMM

 

例子:使用nullif函数,如果姓和名的长度相等,则返回null,不相等,则返回姓的长度

SQL> select first_name,length(first_name) "expr1",last_name,length(last_name) "expr2",nullif(length(first_name),length(last_name)) result from employees;

FIRST_NAME                expr1 LAST_NAME                      expr2     RESULT

-------------------- ---------- ------------------------- ---------- ----------

Kelly                         5 Chung                              5

Karen                         5 Colmenares                        10          5

 

例子:使用coalesce函数,如果manager_id为null,则显示commission_pct的值,如果commission_pct也为null,则显示-1

SQL> select last_name,coalesce(manager_id,commission_pct,-1) comm from employees order by commission_pct;

LAST_NAME                       COMM

------------------------- ----------

Lee                              147

King                              -1

 

 

8、条件表达式

Oracle有2种方式实现条件表达式

  • case语句
  • decode函数

 

 

(1)case语句

OCP课程5:SQL之使用单行函数_第13张图片

需要注意:

  • 寻找when的优先级:从上到下
  • 再多的when,也只有一个出口,即其中有一个满足了expr就马上退出case    
  • 不能把return_expr和else_expr指定为null,而且,expr、comparison_expr和return_expr的数据类型必须相同

 

例子:根据不同的job_id加不同比例的薪水

SQL> select last_name,job_id,salary,

  2  case job_id when 'IT_PROG' then 1.10*salary

  3              when 'ST_CLERK' then 1.15*salary

  4              when 'SA_REP' then 1.20*salary

  5  else salary

  6  end "revised_salary"

  7  from employees;

LAST_NAME                 JOB_ID         SALARY revised_salary

------------------------- ---------- ---------- --------------

OConnell                  SH_CLERK         2600           2600

 

 

(2)decode函数

OCP课程5:SQL之使用单行函数_第14张图片

 

例子:根据不同的job_id加不同比例的薪水

SQL> select last_name,job_id,salary,

  2  decode(job_id,'IT_PROG',1.10*salary,

  3                'ST_CLERK',1.15*salary,

  4                'SA_REP',1.20*salary,

  5         salary)

  6  as revised_salary

  7  from employees;

LAST_NAME                 JOB_ID         SALARY REVISED_SALARY

------------------------- ---------- ---------- --------------

OConnell                  SH_CLERK         2600           2600

 

例子:显示部门编号为80的人员的税率

SQL> select last_name,salary,

  2  decode(trunc(salary/2000,0),

  3  0,0.00,

  4  1,0.09,

  5  2,0.20,

  6  3,0.30,

  7  4,0.40,

  8  5,0.42,

  9  6,0.44,

10    0.45) as tax_rate

11  from employees

12  where department_id=80;

LAST_NAME                     SALARY   TAX_RATE

------------------------- ---------- ----------

Russell                        14000        .45

这章主要讲了数字函数,字符函数,日期函数极其之间的转换,以及对空的处理,和条件表达式。

 

 

9、相关习题

(1)View the Exhibit and examine the description of the ORDERS table. Which two WHERE clause conditions demonstrate the correct usage of conversion functions? (Choose two.)

A.WHERE order_date > TO_DATE('JUL 10 2006','MON DD YYYY')
B.WHERE TO_CHAR(order_date,'MON DD YYYY') = 'JAN 20 2003'
C.WHERE order_date > TO_CHAR(ADD_MONTHS(SYSDATE,6),'MON DD YYYY')
D.WHERE order_date IN ( TO_DATE('Oct 21 2003','Mon DD YYYY'), TO_CHA('NOV 21 2003','Mon DD YYYY') )

 

答案:AB

 

 

(2)View the Exhibit and examine the description of the ORDERS table. Evaluate the following SQL statement: SELECT order_id, customer_id FROM orders WHERE order_date > 'June 30 2001';Which statement is true regarding the execution of this SQL statement ?

A.It would not execute because 'June 30 2001' in the WHERE condition is not enclosed within doublequotation marks. 

B.It  would  execute  and  would  return  ORDER_ID  and  CUSTOMER_ID  for  all  records having ORDER_DATE greater than 'June 30 2001'. 

C.It would not execute because 'June 30 2001' in the WHERE condition cannot be converted implicitly and needs the use of the TO_DATE conversion function for proper execution. 

D.It would not execute because 'June 30 2001' in the WHERE condition cannot be converted implicitly and needs the use of the TO_CHAR conversion function for proper execution.

 

答案:C

 

 

(3)View the Exhibit and examine the description of the EMPLOYEES table. Evaluate the following SQL  statement:  SELECT first_name,  employee_id, NEXT_DAY(ADD_MONTHS(hire_date,  6),  1) "Review" FROM employees;The query was written to retrieve the FIRST_NAME, EMPLOYEE_ID, and review date for employees. The review date is the first Monday after the completion of six months of the hiring. The NLS_TERRITORY parameter is set to AMERICA in the session. Which statement is true regarding this query?

A.The query would execute to give the desired output.
B.The query would not execute because date functions cannot be nested.
C.The query would execute but the output would give review dates that are Sundays.
D.The query would not execute because the NEXT_DAY function accepts a string as argument.

 

答案:C

 

 

(4)Given below is a list of functions and the tasks performed by using these functions, in random order. Function Usage 1) LPAD a) Used to truncate a column, expression, or value to n decimal places 2) TRUNC b) Used to remove heading or trailing or both characters from the character string 3) DECODE c) Pads the character value right-justified to a total width of n character positions 4) TRIM d) Used to return the numeric value for position of a named character from the character string 5) INSTR e) Used to translate an expression after comparing it with each search value ;Which option correctly matches the function names with their usage  ?
A.1-c, 2-b, 3-e, 4-a, 5-d
B.1-e, 2-b, 3-c, 4-a, 5-d
C.1-e, 2-a, 3-c, 4-d, 5-b
D.1-c, 2-a, 3-e, 4-b, 5-d

 

答案:D

 

 

(5)Which three statements are true regarding single-row functions?(Choose three.)
A.They can accept only one argument.
B.They can be nested up to only two levels.
C.They can return multiple values of more than one data type.
D.They can be used in SELECT, WHERE, and ORDER BY clauses.
E.They can modify the data type of the argument that is referenced.
F.They can accept a column name, expression, variable name, or a user-supplied constant as arguments.

 

答案:DEF

 

 

(6)View the Exhibit and examine the description of the EMPLOYEES table. You want to calculate the total remuneration for each employee. Total remuneration is the sum of the annual salary and the percentage commission earned for a year. Only a few employees earn commission. Which SQL statement would you execute to get the desired output? 

A.SELECT first_name, salary, salary*12+salary*commission_pct "Total" FROM EMPLOYEES;
B.SELECT first_name, salary, salary*12+NVL((salary*commission_pct), 0) "Total" FROM EMPLOYEES;
C.SELECT first_name, salary, salary*12+ NVL(salary, 0)*commission_pct "Total" FROM EMPLOYEES;
D.SELECT first_name, salary, salary*12+(salary*NVL2(commission_pct, salary,salary+commission_pct))"Total" FROM EMPLOYEES;

 

答案:B

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28536251/viewspace-1839541/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/28536251/viewspace-1839541/

你可能感兴趣的:(OCP课程5:SQL之使用单行函数)