67
3-1 Copyright © 2011, www.OracleOnLinux OracleOnLinux OracleOnLinux OracleOnLinux.cn. All rights reserved. Oracle OCP Oracle OCP Oracle OCP Oracle OCP 考试系列培训 1Z0-007 Lesson3 1Z0-007 Lesson3 1Z0-007 Lesson3 1Z0-007 Lesson3 www www www www . OracleOnLinux OracleOnLinux OracleOnLinux OracleOnLinux . cn cn cn cn

Lesson03 学会使用单行函数

  • Upload
    renguzi

  • View
    812

  • Download
    4

Embed Size (px)

DESCRIPTION

Oracle OCP考试之007第3章,学会使用单行函数

Citation preview

Page 1: Lesson03 学会使用单行函数

3-1 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Oracle OCPOracle OCPOracle OCPOracle OCP 考试系列培训之

1Z0-007 Lesson31Z0-007 Lesson31Z0-007 Lesson31Z0-007 Lesson3wwwwwwwwwwww....OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux....cncncncn

Page 2: Lesson03 学会使用单行函数

3333Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.3-2

Using Single-Row Functions to Using Single-Row Functions to Using Single-Row Functions to Using Single-Row Functions to Customize Output Customize Output Customize Output Customize Output

Page 3: Lesson03 学会使用单行函数

3-3 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

ObjectivesObjectivesObjectivesObjectives

After completing this lesson, you should be able to do After completing this lesson, you should be able to do After completing this lesson, you should be able to do After completing this lesson, you should be able to do the following:the following:the following:the following:• Describe various types of functions that are Describe various types of functions that are Describe various types of functions that are Describe various types of functions that are

available in SQLavailable in SQLavailable in SQLavailable in SQL• Use character, number, and date functions in Use character, number, and date functions in Use character, number, and date functions in Use character, number, and date functions in

SELECTSELECTSELECTSELECT statements statements statements statements• Describe the use of conversion functionsDescribe the use of conversion functionsDescribe the use of conversion functionsDescribe the use of conversion functions

Page 4: Lesson03 学会使用单行函数

3-4 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SQL FunctionsSQL FunctionsSQL FunctionsSQL Functions

FunctionFunctionFunctionFunction

InputInputInputInput

arg 1arg 1arg 1arg 1

arg 2arg 2arg 2arg 2

arg narg narg narg n

Function performs Function performs Function performs Function performs actionactionactionaction

OutputOutputOutputOutput

ResultResultResultResultvaluevaluevaluevalue

Page 5: Lesson03 学会使用单行函数

3-5 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Two Types of SQL FunctionsTwo Types of SQL FunctionsTwo Types of SQL FunctionsTwo Types of SQL Functions

Single-row Single-row Single-row Single-row functionsfunctionsfunctionsfunctions

Multiple-rowMultiple-rowMultiple-rowMultiple-rowfunctionsfunctionsfunctionsfunctions

Return one result Return one result Return one result Return one result per rowper rowper rowper row

Return one result Return one result Return one result Return one result per set of rowsper set of rowsper set of rowsper set of rows

FunctionsFunctionsFunctionsFunctions

Page 6: Lesson03 学会使用单行函数

3-6 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Single-Row FunctionsSingle-Row FunctionsSingle-Row FunctionsSingle-Row Functions

Single-row functions:Single-row functions:Single-row functions:Single-row functions:• Manipulate data itemsManipulate data itemsManipulate data itemsManipulate data items• Accept arguments and Accept arguments and Accept arguments and Accept arguments and return one valuereturn one valuereturn one valuereturn one value• Act on each row that is returnedAct on each row that is returnedAct on each row that is returnedAct on each row that is returned• Return one result per rowReturn one result per rowReturn one result per rowReturn one result per row• May modify the data typeMay modify the data typeMay modify the data typeMay modify the data type((((隐式转换数据类型))))• Can be nestedCan be nestedCan be nestedCan be nested((((可以嵌套,多层嵌套))))• Accept arguments that can be a column or an Accept arguments that can be a column or an Accept arguments that can be a column or an Accept arguments that can be a column or an

expressionexpressionexpressionexpression

function_namefunction_namefunction_namefunction_name [( [( [( [(arg1, arg2,...arg1, arg2,...arg1, arg2,...arg1, arg2,...)])])])]

Page 7: Lesson03 学会使用单行函数

3-7 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Single-Row FunctionsSingle-Row FunctionsSingle-Row FunctionsSingle-Row Functions

ConversionConversionConversionConversion

CharacterCharacterCharacterCharacter

NumberNumberNumberNumber

DateDateDateDate

GeneralGeneralGeneralGeneral Single-row Single-row Single-row Single-row functionsfunctionsfunctionsfunctions

Page 8: Lesson03 学会使用单行函数

3-8 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Character FunctionsCharacter FunctionsCharacter FunctionsCharacter Functions

CharacterCharacterCharacterCharacterfunctionsfunctionsfunctionsfunctions

LOWERLOWERLOWERLOWERUPPERUPPERUPPERUPPERINITCAPINITCAPINITCAPINITCAP

CONCATCONCATCONCATCONCATSUBSTRSUBSTRSUBSTRSUBSTRLENGTHLENGTHLENGTHLENGTHINSTRINSTRINSTRINSTRLPAD | RPADLPAD | RPADLPAD | RPADLPAD | RPADTRIMTRIMTRIMTRIMREPLACEREPLACEREPLACEREPLACE

Case-manipulation Case-manipulation Case-manipulation Case-manipulation functionsfunctionsfunctionsfunctions

Character-manipulationCharacter-manipulationCharacter-manipulationCharacter-manipulationfunctionsfunctionsfunctionsfunctions

Page 9: Lesson03 学会使用单行函数

3-9 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Case-Manipulation FunctionsCase-Manipulation FunctionsCase-Manipulation FunctionsCase-Manipulation Functions

These functions convert case for character strings:These functions convert case for character strings:These functions convert case for character strings:These functions convert case for character strings:

sql coursesql coursesql coursesql courseLOWER(LOWER(LOWER(LOWER(''''SQL CourseSQL CourseSQL CourseSQL Course''''))))

Sql CourseSql CourseSql CourseSql CourseINITCAP(INITCAP(INITCAP(INITCAP(''''SQL CourseSQL CourseSQL CourseSQL Course''''))))

SQL COURSESQL COURSESQL COURSESQL COURSEUPPER(UPPER(UPPER(UPPER(''''SQL CourseSQL CourseSQL CourseSQL Course''''))))

ResultResultResultResultFunctionFunctionFunctionFunction

Page 10: Lesson03 学会使用单行函数

3-10 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT employee_id, last_name, department_idSELECT employee_id, last_name, department_idSELECT employee_id, last_name, department_idSELECT employee_id, last_name, department_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE LOWER(last_name) = 'higgins';WHERE LOWER(last_name) = 'higgins';WHERE LOWER(last_name) = 'higgins';WHERE LOWER(last_name) = 'higgins';

Using Case-Manipulation FunctionsUsing Case-Manipulation FunctionsUsing Case-Manipulation FunctionsUsing Case-Manipulation Functions

Display the employee number, name, and department Display the employee number, name, and department Display the employee number, name, and department Display the employee number, name, and department number for employee Higgins:number for employee Higgins:number for employee Higgins:number for employee Higgins:

SELECT employee_id, last_name, department_idSELECT employee_id, last_name, department_idSELECT employee_id, last_name, department_idSELECT employee_id, last_name, department_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE last_name = 'higgins';WHERE last_name = 'higgins';WHERE last_name = 'higgins';WHERE last_name = 'higgins';no rows selectedno rows selectedno rows selectedno rows selected

Page 11: Lesson03 学会使用单行函数

3-11 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Character-Manipulation FunctionsCharacter-Manipulation FunctionsCharacter-Manipulation FunctionsCharacter-Manipulation Functions

These functions manipulate character strings:These functions manipulate character strings:These functions manipulate character strings:These functions manipulate character strings:

BLACK and BLUE BLACK and BLUE BLACK and BLUE BLACK and BLUE REPLACEREPLACEREPLACEREPLACE('JACK and JUE','J','BL') ('JACK and JUE','J','BL') ('JACK and JUE','J','BL') ('JACK and JUE','J','BL')

10101010LENGTH('HelloWorld')LENGTH('HelloWorld')LENGTH('HelloWorld')LENGTH('HelloWorld')

6666INSTR('HelloWorld', 'W')INSTR('HelloWorld', 'W')INSTR('HelloWorld', 'W')INSTR('HelloWorld', 'W')

********************24000240002400024000LPAD(salary,10,LPAD(salary,10,LPAD(salary,10,LPAD(salary,10,''''****''''))))

24000240002400024000********************RPAD(salary, 10, 'RPAD(salary, 10, 'RPAD(salary, 10, 'RPAD(salary, 10, '****')')')')

HelloWorldHelloWorldHelloWorldHelloWorldCONCAT('Hello', 'World')CONCAT('Hello', 'World')CONCAT('Hello', 'World')CONCAT('Hello', 'World')

elloWorldelloWorldelloWorldelloWorldTRIM('H' FROM 'HelloWorld')TRIM('H' FROM 'HelloWorld')TRIM('H' FROM 'HelloWorld')TRIM('H' FROM 'HelloWorld')

HelloHelloHelloHelloSUBSTR('HelloWorldSUBSTR('HelloWorldSUBSTR('HelloWorldSUBSTR('HelloWorld'''',1,5),1,5),1,5),1,5)

ResultResultResultResultFunctionFunctionFunctionFunction

Page 12: Lesson03 学会使用单行函数

3-12 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT employee_id, CONCAT(first_name, last_name) NAME, SELECT employee_id, CONCAT(first_name, last_name) NAME, SELECT employee_id, CONCAT(first_name, last_name) NAME, SELECT employee_id, CONCAT(first_name, last_name) NAME, job_id, LENGTH (last_name), job_id, LENGTH (last_name), job_id, LENGTH (last_name), job_id, LENGTH (last_name), INSTR(last_name, 'a') "Contains 'a'?" INSTR(last_name, 'a') "Contains 'a'?" INSTR(last_name, 'a') "Contains 'a'?" INSTR(last_name, 'a') "Contains 'a'?"FROM employeesFROM employeesFROM employeesFROM employeesWHERE SUBSTR(job_id, 4) = 'REP';WHERE SUBSTR(job_id, 4) = 'REP';WHERE SUBSTR(job_id, 4) = 'REP';WHERE SUBSTR(job_id, 4) = 'REP';

Using the Character-Manipulation Using the Character-Manipulation Using the Character-Manipulation Using the Character-Manipulation FunctionsFunctionsFunctionsFunctions

2222

33331111 2222

1111

3333

Page 13: Lesson03 学会使用单行函数

3-13 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Number FunctionsNumber FunctionsNumber FunctionsNumber Functions

• ROUNDROUNDROUNDROUND: Rounds value to specified decimal: Rounds value to specified decimal: Rounds value to specified decimal: Rounds value to specified decimal• TRUNCTRUNCTRUNCTRUNC: Truncates value to specified decimal: Truncates value to specified decimal: Truncates value to specified decimal: Truncates value to specified decimal• MODMODMODMOD: Returns remainder of division: Returns remainder of division: Returns remainder of division: Returns remainder of division

100100100100MOD(1600, 300)MOD(1600, 300)MOD(1600, 300)MOD(1600, 300)

45.9345.9345.9345.93ROUND(45.926, 2)ROUND(45.926, 2)ROUND(45.926, 2)ROUND(45.926, 2)

45.9245.9245.9245.92TRUNC(45.926, 2)TRUNC(45.926, 2)TRUNC(45.926, 2)TRUNC(45.926, 2)

ResultResultResultResultFunctionFunctionFunctionFunction

Page 14: Lesson03 学会使用单行函数

3-14 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT ROUND(45.923,2), ROUND(45.923,0),SELECT ROUND(45.923,2), ROUND(45.923,0),SELECT ROUND(45.923,2), ROUND(45.923,0),SELECT ROUND(45.923,2), ROUND(45.923,0), ROUND(45.923,-1) ROUND(45.923,-1) ROUND(45.923,-1) ROUND(45.923,-1)FROM DUAL;FROM DUAL;FROM DUAL;FROM DUAL;

Using the Using the Using the Using the ROUNDROUNDROUNDROUND Function Function Function Function

DUALDUALDUALDUAL is a dummy table that you can use to view results is a dummy table that you can use to view results is a dummy table that you can use to view results is a dummy table that you can use to view results from functions and calculations.from functions and calculations.from functions and calculations.from functions and calculations.

3333

33331111 2222

1111 2222

Page 15: Lesson03 学会使用单行函数

3-15 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Using the Using the Using the Using the TRUNCTRUNCTRUNCTRUNC Function Function Function Function

SELECT TRUNC(45.923,2), TRUNC(45.923),SELECT TRUNC(45.923,2), TRUNC(45.923),SELECT TRUNC(45.923,2), TRUNC(45.923),SELECT TRUNC(45.923,2), TRUNC(45.923), TRUNC(45.923,-1) TRUNC(45.923,-1) TRUNC(45.923,-1) TRUNC(45.923,-1)FROM DUAL;FROM DUAL;FROM DUAL;FROM DUAL;

3333

33331111 2222

1111 2222

Page 16: Lesson03 学会使用单行函数

3-16 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, salary, MOD(salary, 5000)SELECT last_name, salary, MOD(salary, 5000)SELECT last_name, salary, MOD(salary, 5000)SELECT last_name, salary, MOD(salary, 5000)FROM employeesFROM employeesFROM employeesFROM employeesWHERE job_id = 'SA_REP';WHERE job_id = 'SA_REP';WHERE job_id = 'SA_REP';WHERE job_id = 'SA_REP';

Using the Using the Using the Using the MODMODMODMOD Function Function Function Function

For all employees with job title of Sales Representative, For all employees with job title of Sales Representative, For all employees with job title of Sales Representative, For all employees with job title of Sales Representative, calculate the remainder of the salary after it is divided calculate the remainder of the salary after it is divided calculate the remainder of the salary after it is divided calculate the remainder of the salary after it is divided by 5,000.by 5,000.by 5,000.by 5,000.

Page 17: Lesson03 学会使用单行函数

3-17 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, hire_dateSELECT last_name, hire_dateSELECT last_name, hire_dateSELECT last_name, hire_dateFROM employeesFROM employeesFROM employeesFROM employeesWHERE hire_date < WHERE hire_date < WHERE hire_date < WHERE hire_date < ''''''''01-FEB-8801-FEB-8801-FEB-8801-FEB-88';';';';';';';';

Working with DatesWorking with DatesWorking with DatesWorking with Dates

• The Oracle database stores dates in an internal numeric The Oracle database stores dates in an internal numeric The Oracle database stores dates in an internal numeric The Oracle database stores dates in an internal numeric format: century, year, month, day, hours, minutes, and format: century, year, month, day, hours, minutes, and format: century, year, month, day, hours, minutes, and format: century, year, month, day, hours, minutes, and seconds.seconds.seconds.seconds.

• The default date display format is DD-MON-RR.The default date display format is DD-MON-RR.The default date display format is DD-MON-RR.The default date display format is DD-MON-RR.– Enables you to store 21st-century dates in theEnables you to store 21st-century dates in theEnables you to store 21st-century dates in theEnables you to store 21st-century dates in the

20th century by specifying only the last two digits 20th century by specifying only the last two digits 20th century by specifying only the last two digits 20th century by specifying only the last two digits of the year of the year of the year of the year

– Enables you to store 20th-century dates in theEnables you to store 20th-century dates in theEnables you to store 20th-century dates in theEnables you to store 20th-century dates in the21st century in the same way 21st century in the same way 21st century in the same way 21st century in the same way

Page 18: Lesson03 学会使用单行函数

3-18 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Working with DatesWorking with DatesWorking with DatesWorking with Dates

SYSDATESYSDATESYSDATESYSDATE is a function that returns: is a function that returns: is a function that returns: is a function that returns:• Date Date Date Date • TimeTimeTimeTime

Page 19: Lesson03 学会使用单行函数

3-19 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Arithmetic with DatesArithmetic with DatesArithmetic with DatesArithmetic with Dates

• Add or subtract a number to or from a date for a Add or subtract a number to or from a date for a Add or subtract a number to or from a date for a Add or subtract a number to or from a date for a resultant date value.resultant date value.resultant date value.resultant date value.

• Subtract two dates to find the number of days Subtract two dates to find the number of days Subtract two dates to find the number of days Subtract two dates to find the number of days between those dates.between those dates.between those dates.between those dates.

• Add hours to a date by dividing the number of Add hours to a date by dividing the number of Add hours to a date by dividing the number of Add hours to a date by dividing the number of hours by 24.hours by 24.hours by 24.hours by 24.

Page 20: Lesson03 学会使用单行函数

3-20 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKSSELECT last_name, (SYSDATE-hire_date)/7 AS WEEKSSELECT last_name, (SYSDATE-hire_date)/7 AS WEEKSSELECT last_name, (SYSDATE-hire_date)/7 AS WEEKSFROM employeesFROM employeesFROM employeesFROM employeesWHERE department_id = 90;WHERE department_id = 90;WHERE department_id = 90;WHERE department_id = 90;

Using Arithmetic OperatorsUsing Arithmetic OperatorsUsing Arithmetic OperatorsUsing Arithmetic Operatorswith Dateswith Dateswith Dateswith Dates

Page 21: Lesson03 学会使用单行函数

3-21 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Date FunctionsDate FunctionsDate FunctionsDate Functions

Next day of the date specifiedNext day of the date specifiedNext day of the date specifiedNext day of the date specifiedNEXT_DAYNEXT_DAYNEXT_DAYNEXT_DAY

Last day of the monthLast day of the monthLast day of the monthLast day of the monthLAST_DAYLAST_DAYLAST_DAYLAST_DAY

Round dateRound dateRound dateRound dateROUNDROUNDROUNDROUND

Truncate dateTruncate dateTruncate dateTruncate dateTRUNCTRUNCTRUNCTRUNC

Number of months between two datesNumber of months between two datesNumber of months between two datesNumber of months between two datesMONTHS_BETWEENMONTHS_BETWEENMONTHS_BETWEENMONTHS_BETWEEN

Add calendar months to dateAdd calendar months to dateAdd calendar months to dateAdd calendar months to dateADD_MONTHSADD_MONTHSADD_MONTHSADD_MONTHS

ResultResultResultResultFunctionFunctionFunctionFunction

Page 22: Lesson03 学会使用单行函数

3-22 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Using Date FunctionsUsing Date FunctionsUsing Date FunctionsUsing Date Functions

'08-SEP-95''08-SEP-95''08-SEP-95''08-SEP-95'NEXT_DAY ('01-SEP-95','FRIDAY')NEXT_DAY ('01-SEP-95','FRIDAY')NEXT_DAY ('01-SEP-95','FRIDAY')NEXT_DAY ('01-SEP-95','FRIDAY')

'28-FEB-95''28-FEB-95''28-FEB-95''28-FEB-95'LAST_DAY ('01-FEB-95')LAST_DAY ('01-FEB-95')LAST_DAY ('01-FEB-95')LAST_DAY ('01-FEB-95')

19.677419419.677419419.677419419.6774194MONTHS_BETWEENMONTHS_BETWEENMONTHS_BETWEENMONTHS_BETWEEN ('01-SEP-95','11-JAN-94') ('01-SEP-95','11-JAN-94') ('01-SEP-95','11-JAN-94') ('01-SEP-95','11-JAN-94')

'11-JUL-94''11-JUL-94''11-JUL-94''11-JUL-94'ADD_MONTHS ('11-JAN-94',6)ADD_MONTHS ('11-JAN-94',6)ADD_MONTHS ('11-JAN-94',6)ADD_MONTHS ('11-JAN-94',6)

ResultResultResultResultFunctionFunctionFunctionFunction

Page 23: Lesson03 学会使用单行函数

3-23 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Using Date FunctionsUsing Date FunctionsUsing Date FunctionsUsing Date Functions

Assume Assume Assume Assume SYSDATE = '25-JUL-03'SYSDATE = '25-JUL-03'SYSDATE = '25-JUL-03'SYSDATE = '25-JUL-03'::::

01-JUL-0301-JUL-0301-JUL-0301-JUL-03TRUNC(SYSDATE ,'MONTH')TRUNC(SYSDATE ,'MONTH')TRUNC(SYSDATE ,'MONTH')TRUNC(SYSDATE ,'MONTH')

01-JAN-0301-JAN-0301-JAN-0301-JAN-03TRUNC(SYSDATE ,'YEAR')TRUNC(SYSDATE ,'YEAR')TRUNC(SYSDATE ,'YEAR')TRUNC(SYSDATE ,'YEAR')

01-AUG-0301-AUG-0301-AUG-0301-AUG-03ROUND(SYSDATE,'MONTH')ROUND(SYSDATE,'MONTH')ROUND(SYSDATE,'MONTH')ROUND(SYSDATE,'MONTH')

01-JAN-0401-JAN-0401-JAN-0401-JAN-04ROUND(SYSDATE ,'YEAR')ROUND(SYSDATE ,'YEAR')ROUND(SYSDATE ,'YEAR')ROUND(SYSDATE ,'YEAR')

ResultResultResultResultFunctionFunctionFunctionFunction

Page 24: Lesson03 学会使用单行函数

3-24 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3: Overview of Part 1Practice 3: Overview of Part 1Practice 3: Overview of Part 1Practice 3: Overview of Part 1

This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:• Writing a query that displays the current date Writing a query that displays the current date Writing a query that displays the current date Writing a query that displays the current date • Creating queries that require the use of numeric, Creating queries that require the use of numeric, Creating queries that require the use of numeric, Creating queries that require the use of numeric,

character, and date functionscharacter, and date functionscharacter, and date functionscharacter, and date functions• Performing calculations of years and months of Performing calculations of years and months of Performing calculations of years and months of Performing calculations of years and months of

service for an employeeservice for an employeeservice for an employeeservice for an employee

Page 25: Lesson03 学会使用单行函数

3-25 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Conversion FunctionsConversion FunctionsConversion FunctionsConversion Functions

Implicit data typeImplicit data typeImplicit data typeImplicit data typeconversionconversionconversionconversion

Explicit data typeExplicit data typeExplicit data typeExplicit data typeconversionconversionconversionconversion

Data typeData typeData typeData typeconversionconversionconversionconversion

Page 26: Lesson03 学会使用单行函数

3-26 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Implicit Data Type ConversionImplicit Data Type ConversionImplicit Data Type ConversionImplicit Data Type Conversion

For assignments, the Oracle server can automatically For assignments, the Oracle server can automatically For assignments, the Oracle server can automatically For assignments, the Oracle server can automatically convert the following:convert the following:convert the following:convert the following:

VARCHAR2VARCHAR2VARCHAR2VARCHAR2NUMBERNUMBERNUMBERNUMBER

VARCHAR2VARCHAR2VARCHAR2VARCHAR2DATEDATEDATEDATE

NUMBERNUMBERNUMBERNUMBERVARCHAR2 or CHARVARCHAR2 or CHARVARCHAR2 or CHARVARCHAR2 or CHAR

DATEDATEDATEDATEVARCHAR2 or CHARVARCHAR2 or CHARVARCHAR2 or CHARVARCHAR2 or CHAR

ToToToToFromFromFromFrom

Page 27: Lesson03 学会使用单行函数

3-27 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Implicit Data Type ConversionImplicit Data Type ConversionImplicit Data Type ConversionImplicit Data Type Conversion

For expression evaluation, the Oracle Server can For expression evaluation, the Oracle Server can For expression evaluation, the Oracle Server can For expression evaluation, the Oracle Server can automatically convert the following:automatically convert the following:automatically convert the following:automatically convert the following:

NUMBERNUMBERNUMBERNUMBERVARCHAR2 or CHARVARCHAR2 or CHARVARCHAR2 or CHARVARCHAR2 or CHAR

DATEDATEDATEDATEVARCHAR2 or CHARVARCHAR2 or CHARVARCHAR2 or CHARVARCHAR2 or CHAR

ToToToToFromFromFromFrom

SELECT last_name, SELECT last_name, SELECT last_name, SELECT last_name, salarysalarysalarysalaryFROM employeesFROM employeesFROM employeesFROM employeesWHERE WHERE WHERE WHERE salary>'10000'salary>'10000'salary>'10000'salary>'10000'

Page 28: Lesson03 学会使用单行函数

3-28 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Explicit Data Type ConversionExplicit Data Type ConversionExplicit Data Type ConversionExplicit Data Type Conversion

NUMBERNUMBERNUMBERNUMBER CHARACTERCHARACTERCHARACTERCHARACTER

TO_CHARTO_CHARTO_CHARTO_CHAR

TO_NUMBERTO_NUMBERTO_NUMBERTO_NUMBER

DATEDATEDATEDATE

TO_CHARTO_CHARTO_CHARTO_CHAR

TO_DATETO_DATETO_DATETO_DATE

Page 29: Lesson03 学会使用单行函数

3-29 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Explicit Data Type ConversionExplicit Data Type ConversionExplicit Data Type ConversionExplicit Data Type Conversion

NUMBERNUMBERNUMBERNUMBER CHARACTERCHARACTERCHARACTERCHARACTER

TO_CHARTO_CHARTO_CHARTO_CHAR

TO_NUMBERTO_NUMBERTO_NUMBERTO_NUMBER

DATEDATEDATEDATE

TO_CHARTO_CHARTO_CHARTO_CHAR

TO_DATETO_DATETO_DATETO_DATE

Page 30: Lesson03 学会使用单行函数

3-30 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Using the Using the Using the Using the TO_CHARTO_CHARTO_CHARTO_CHAR Function with Dates Function with Dates Function with Dates Function with Dates

The format model:The format model:The format model:The format model:• Must be enclosed by single quotation marksMust be enclosed by single quotation marksMust be enclosed by single quotation marksMust be enclosed by single quotation marks• Is case-sensitiveIs case-sensitiveIs case-sensitiveIs case-sensitive• Can include any valid date format elementCan include any valid date format elementCan include any valid date format elementCan include any valid date format element• Has an Has an Has an Has an fmfmfmfm element to remove padded blanks or element to remove padded blanks or element to remove padded blanks or element to remove padded blanks or

suppress leading zerossuppress leading zerossuppress leading zerossuppress leading zeros• Is separated from the date value by a commaIs separated from the date value by a commaIs separated from the date value by a commaIs separated from the date value by a comma

TO_CHAR(TO_CHAR(TO_CHAR(TO_CHAR(date, date, date, date, ''''format_modelformat_modelformat_modelformat_model')')')')

Page 31: Lesson03 学会使用单行函数

3-31 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Elements of the Date Format ModelElements of the Date Format ModelElements of the Date Format ModelElements of the Date Format Model

Three-letter abbreviation of the day of the Three-letter abbreviation of the day of the Three-letter abbreviation of the day of the Three-letter abbreviation of the day of the weekweekweekweek

DYDYDYDY

Full name of the day of the weekFull name of the day of the weekFull name of the day of the weekFull name of the day of the weekDAYDAYDAYDAY

Two-digit value for monthTwo-digit value for monthTwo-digit value for monthTwo-digit value for monthMMMMMMMM

Full name of the monthFull name of the monthFull name of the monthFull name of the monthMONTHMONTHMONTHMONTH

Three-letter abbreviation of the monthThree-letter abbreviation of the monthThree-letter abbreviation of the monthThree-letter abbreviation of the monthMONMONMONMON

Numeric day of the monthNumeric day of the monthNumeric day of the monthNumeric day of the monthDDDDDDDD

Full year in numbersFull year in numbersFull year in numbersFull year in numbersYYYYYYYYYYYYYYYY

Year spelled out (in English)Year spelled out (in English)Year spelled out (in English)Year spelled out (in English)YEARYEARYEARYEAR

ResultResultResultResultElementElementElementElement

Page 32: Lesson03 学会使用单行函数

3-32 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Elements of the Date Format ModelElements of the Date Format ModelElements of the Date Format ModelElements of the Date Format Model

• Time elements format the time portion of the date:Time elements format the time portion of the date:Time elements format the time portion of the date:Time elements format the time portion of the date:

• Add character strings by enclosing them in double Add character strings by enclosing them in double Add character strings by enclosing them in double Add character strings by enclosing them in double quotation marks:quotation marks:quotation marks:quotation marks:

• Number suffixes spell out numbers:Number suffixes spell out numbers:Number suffixes spell out numbers:Number suffixes spell out numbers:

DD "of" MONTHDD "of" MONTHDD "of" MONTHDD "of" MONTH 12 of OCTOBER12 of OCTOBER12 of OCTOBER12 of OCTOBER

ddspthddspthddspthddspth fourteenthfourteenthfourteenthfourteenth

HH24:MI:SS AMHH24:MI:SS AMHH24:MI:SS AMHH24:MI:SS AM 15:45:32 PM15:45:32 PM15:45:32 PM15:45:32 PM

Page 33: Lesson03 学会使用单行函数

3-33 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name,SELECT last_name,SELECT last_name,SELECT last_name, TO_CHAR(hire_date, 'fmDD Month YYYY') TO_CHAR(hire_date, 'fmDD Month YYYY') TO_CHAR(hire_date, 'fmDD Month YYYY') TO_CHAR(hire_date, 'fmDD Month YYYY') AS HIREDATE AS HIREDATE AS HIREDATE AS HIREDATEFROM employees;FROM employees;FROM employees;FROM employees;

Using the Using the Using the Using the TO_CHARTO_CHARTO_CHARTO_CHAR Function with Dates Function with Dates Function with Dates Function with Dates

…………

Page 34: Lesson03 学会使用单行函数

3-34 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Using the Using the Using the Using the TO_CHARTO_CHARTO_CHARTO_CHAR Function with Numbers Function with Numbers Function with Numbers Function with Numbers

These are some of the format elements that you can These are some of the format elements that you can These are some of the format elements that you can These are some of the format elements that you can use with the use with the use with the use with the TO_CHARTO_CHARTO_CHARTO_CHAR function to display a number function to display a number function to display a number function to display a number value as a character:value as a character:value as a character:value as a character:

Prints a decimal pointPrints a decimal pointPrints a decimal pointPrints a decimal point....

Prints a comma as thousands indicatorPrints a comma as thousands indicatorPrints a comma as thousands indicatorPrints a comma as thousands indicator,,,,

Places a floating dollar signPlaces a floating dollar signPlaces a floating dollar signPlaces a floating dollar sign$$$$

Uses the floating local currency symbolUses the floating local currency symbolUses the floating local currency symbolUses the floating local currency symbolLLLL

Represents a numberRepresents a numberRepresents a numberRepresents a number9999

Forces a zero to be displayedForces a zero to be displayedForces a zero to be displayedForces a zero to be displayed0000

ResultResultResultResultElementElementElementElement

TO_CHAR(TO_CHAR(TO_CHAR(TO_CHAR(number, number, number, number, ''''format_modelformat_modelformat_modelformat_model')')')')

Page 35: Lesson03 学会使用单行函数

3-35 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT TO_CHAR(salary, '$99,999.00') SALARYSELECT TO_CHAR(salary, '$99,999.00') SALARYSELECT TO_CHAR(salary, '$99,999.00') SALARYSELECT TO_CHAR(salary, '$99,999.00') SALARYFROM employeesFROM employeesFROM employeesFROM employeesWHERE last_name = 'Ernst';WHERE last_name = 'Ernst';WHERE last_name = 'Ernst';WHERE last_name = 'Ernst';

Using the Using the Using the Using the TO_CHARTO_CHARTO_CHARTO_CHAR Function with Numbers Function with Numbers Function with Numbers Function with Numbers

Page 36: Lesson03 学会使用单行函数

3-36 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Using the Using the Using the Using the TO_NUMBERTO_NUMBERTO_NUMBERTO_NUMBER and and and and TO_DATETO_DATETO_DATETO_DATE Functions Functions Functions Functions

• Convert a character string to a number format Convert a character string to a number format Convert a character string to a number format Convert a character string to a number format using the using the using the using the TO_NUMBERTO_NUMBERTO_NUMBERTO_NUMBER function: function: function: function:

• Convert a character string to a date format using Convert a character string to a date format using Convert a character string to a date format using Convert a character string to a date format using the the the the TO_DATETO_DATETO_DATETO_DATE function: function: function: function:

• These functions have an These functions have an These functions have an These functions have an fxfxfxfx modifier. This modifier. This modifier. This modifier. This modifier specifies the exact matching for the modifier specifies the exact matching for the modifier specifies the exact matching for the modifier specifies the exact matching for the character argument and date format model of a character argument and date format model of a character argument and date format model of a character argument and date format model of a TO_DATETO_DATETO_DATETO_DATE function. function. function. function.

TO_NUMBER(TO_NUMBER(TO_NUMBER(TO_NUMBER(charcharcharchar[[[[, , , , ''''format_modelformat_modelformat_modelformat_model'])'])'])'])

TO_DATE(TO_DATE(TO_DATE(TO_DATE(charcharcharchar[, '[, '[, '[, 'format_modelformat_modelformat_modelformat_model'])'])'])'])

Page 37: Lesson03 学会使用单行函数

3-37 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Using the Using the Using the Using the TO_NUMBERTO_NUMBERTO_NUMBERTO_NUMBER and and and and TO_DATETO_DATETO_DATETO_DATE FunctionsFunctionsFunctionsFunctions

• Convert a character string to a number format Convert a character string to a number format Convert a character string to a number format Convert a character string to a number format using the using the using the using the TO_NUMBERTO_NUMBERTO_NUMBERTO_NUMBER function: function: function: function:

• Convert a character string to a date format using Convert a character string to a date format using Convert a character string to a date format using Convert a character string to a date format using the the the the TO_DATETO_DATETO_DATETO_DATE function: function: function: function:

• These functions have an These functions have an These functions have an These functions have an fxfxfxfx modifier. This modifier. This modifier. This modifier. This modifier specifies the exact matching for the modifier specifies the exact matching for the modifier specifies the exact matching for the modifier specifies the exact matching for the character argument and date format model of a character argument and date format model of a character argument and date format model of a character argument and date format model of a TO_DATETO_DATETO_DATETO_DATE function function function function

TO_NUMBER(TO_NUMBER(TO_NUMBER(TO_NUMBER(charcharcharchar[[[[, , , , ''''format_modelformat_modelformat_modelformat_model'])'])'])'])

TO_DATE(TO_DATE(TO_DATE(TO_DATE(charcharcharchar[, '[, '[, '[, 'format_modelformat_modelformat_modelformat_model'])'])'])'])

Page 38: Lesson03 学会使用单行函数

3-38 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

RRRRRRRR Date Format Date Format Date Format Date Format

Current YearCurrent YearCurrent YearCurrent Year1995199519951995199519951995199520012001200120012001200120012001

Specified DateSpecified DateSpecified DateSpecified Date27-OCT-9527-OCT-9527-OCT-9527-OCT-9527-OCT-1727-OCT-1727-OCT-1727-OCT-1727-OCT-1727-OCT-1727-OCT-1727-OCT-1727-OCT-9527-OCT-9527-OCT-9527-OCT-95

RR FormatRR FormatRR FormatRR Format1995199519951995201720172017201720172017201720171995199519951995

YY FormatYY FormatYY FormatYY Format1995199519951995191719171917191720172017201720172095209520952095

If two digits If two digits If two digits If two digits of the of the of the of the current current current current year are:year are:year are:year are:

0000––––49494949

0000––––49494949 50505050––––99999999

50505050––––99999999

The return date is in The return date is in The return date is in The return date is in the current centurythe current centurythe current centurythe current century

The return date is in The return date is in The return date is in The return date is in the century after the century after the century after the century after the current onethe current onethe current onethe current one

The return date is in The return date is in The return date is in The return date is in the century before the century before the century before the century before the current onethe current onethe current onethe current oneThe return date is in The return date is in The return date is in The return date is in the current centurythe current centurythe current centurythe current century

If the specified two-digit year is:If the specified two-digit year is:If the specified two-digit year is:If the specified two-digit year is:

Page 39: Lesson03 学会使用单行函数

3-39 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Example of Example of Example of Example of RRRRRRRR Date Format Date Format Date Format Date Format

To find employees hired prior to 1990, use the To find employees hired prior to 1990, use the To find employees hired prior to 1990, use the To find employees hired prior to 1990, use the RRRRRRRR date date date date format, which produces the same results whether the format, which produces the same results whether the format, which produces the same results whether the format, which produces the same results whether the command is run in 1999 or now:command is run in 1999 or now:command is run in 1999 or now:command is run in 1999 or now:

SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')FROM employeesFROM employeesFROM employeesFROM employeesWHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');WHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');WHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');WHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');

Page 40: Lesson03 学会使用单行函数

3-40 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Nesting FunctionsNesting FunctionsNesting FunctionsNesting Functions

• Single-row functions can be nested to any level.Single-row functions can be nested to any level.Single-row functions can be nested to any level.Single-row functions can be nested to any level.• Nested functions are evaluated from deepest level Nested functions are evaluated from deepest level Nested functions are evaluated from deepest level Nested functions are evaluated from deepest level

to the least deep level.to the least deep level.to the least deep level.to the least deep level.

F3(F3(F3(F3(F2F2F2F2((((F1(col,arg1)F1(col,arg1)F1(col,arg1)F1(col,arg1),,,,arg2arg2arg2arg2),arg3)),arg3)),arg3)),arg3)

StepStepStepStep 1 = 1 = 1 = 1 = ResultResultResultResult 1111StepStepStepStep 2 = 2 = 2 = 2 = ResultResultResultResult 2222

StepStepStepStep 3 = 3 = 3 = 3 = ResultResultResultResult 3 3 3 3

Page 41: Lesson03 学会使用单行函数

3-41 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name,SELECT last_name,SELECT last_name,SELECT last_name, UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US')) UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US')) UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US')) UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US'))FROM employeesFROM employeesFROM employeesFROM employeesWHERE department_id = 60;WHERE department_id = 60;WHERE department_id = 60;WHERE department_id = 60;

Nesting FunctionsNesting FunctionsNesting FunctionsNesting Functions

SELECT last_name,SELECT last_name,SELECT last_name,SELECT last_name, NVL( NVL( NVL( NVL(TO_CHARTO_CHARTO_CHARTO_CHAR(manager_id), 'No Manager')(manager_id), 'No Manager')(manager_id), 'No Manager')(manager_id), 'No Manager')FROM employeesFROM employeesFROM employeesFROM employeesWHERE manager_id IS NULL;WHERE manager_id IS NULL;WHERE manager_id IS NULL;WHERE manager_id IS NULL;

Page 42: Lesson03 学会使用单行函数

3-42 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

General FunctionsGeneral FunctionsGeneral FunctionsGeneral Functions

The following functions work with any data type and The following functions work with any data type and The following functions work with any data type and The following functions work with any data type and pertain to using nulls:pertain to using nulls:pertain to using nulls:pertain to using nulls:• NVL (expr1, expr2)NVL (expr1, expr2)NVL (expr1, expr2)NVL (expr1, expr2)• NVL2 (expr1, expr2, expr3)NVL2 (expr1, expr2, expr3)NVL2 (expr1, expr2, expr3)NVL2 (expr1, expr2, expr3)• NULLIF (expr1, expr2)NULLIF (expr1, expr2)NULLIF (expr1, expr2)NULLIF (expr1, expr2)• COALESCE (expr1, expr2, ..., exprCOALESCE (expr1, expr2, ..., exprCOALESCE (expr1, expr2, ..., exprCOALESCE (expr1, expr2, ..., exprnnnn))))

Page 43: Lesson03 学会使用单行函数

3-43 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

NVLNVLNVLNVL Function Function Function Function

Converts a null value to an actual value:Converts a null value to an actual value:Converts a null value to an actual value:Converts a null value to an actual value:• Data types that can be used are date, character, Data types that can be used are date, character, Data types that can be used are date, character, Data types that can be used are date, character,

and number.and number.and number.and number.• Data types must matchData types must matchData types must matchData types must match::::

– NVL(commission_pct,0)NVL(commission_pct,0)NVL(commission_pct,0)NVL(commission_pct,0)

– NVL(hire_date,'01-JAN-97')NVL(hire_date,'01-JAN-97')NVL(hire_date,'01-JAN-97')NVL(hire_date,'01-JAN-97')

– NVL(job_id,'No Job Yet')NVL(job_id,'No Job Yet')NVL(job_id,'No Job Yet')NVL(job_id,'No Job Yet')

SELECT last_name,SELECT last_name,SELECT last_name,SELECT last_name, NVL( NVL( NVL( NVL(TO_CHARTO_CHARTO_CHARTO_CHAR(manager_id), 'No Manager')(manager_id), 'No Manager')(manager_id), 'No Manager')(manager_id), 'No Manager')FROM employeesFROM employeesFROM employeesFROM employeesWHERE manager_id IS NULL;WHERE manager_id IS NULL;WHERE manager_id IS NULL;WHERE manager_id IS NULL;

Page 44: Lesson03 学会使用单行函数

3-44 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, salary, NVL(commission_pct, 0),SELECT last_name, salary, NVL(commission_pct, 0),SELECT last_name, salary, NVL(commission_pct, 0),SELECT last_name, salary, NVL(commission_pct, 0), (salary (salary (salary (salary****12) + (salary12) + (salary12) + (salary12) + (salary****12121212****NVL(commission_pct, 0)) AN_SALNVL(commission_pct, 0)) AN_SALNVL(commission_pct, 0)) AN_SALNVL(commission_pct, 0)) AN_SALFROM employees;FROM employees;FROM employees;FROM employees;

Using the Using the Using the Using the NVLNVLNVLNVL Function Function Function Function

…………

1111

1111 2222

2222

Page 45: Lesson03 学会使用单行函数

3-45 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, salary, commission_pct,SELECT last_name, salary, commission_pct,SELECT last_name, salary, commission_pct,SELECT last_name, salary, commission_pct, NVL2(commission_pct, NVL2(commission_pct, NVL2(commission_pct, NVL2(commission_pct, 'SAL+COMM', 'SAL') income 'SAL+COMM', 'SAL') income 'SAL+COMM', 'SAL') income 'SAL+COMM', 'SAL') incomeFROM employees WHERE department_id IN (50, 80);FROM employees WHERE department_id IN (50, 80);FROM employees WHERE department_id IN (50, 80);FROM employees WHERE department_id IN (50, 80);

Using the Using the Using the Using the NVL2NVL2NVL2NVL2 Function Function Function Function

1111 2222

22221111

Page 46: Lesson03 学会使用单行函数

3-46 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT first_name, LENGTH(first_name) "expr1", SELECT first_name, LENGTH(first_name) "expr1", SELECT first_name, LENGTH(first_name) "expr1", SELECT first_name, LENGTH(first_name) "expr1", last_name, LENGTH(last_name) "expr2", last_name, LENGTH(last_name) "expr2", last_name, LENGTH(last_name) "expr2", last_name, LENGTH(last_name) "expr2", NULLIF(LENGTH(first_name), LENGTH(last_name)) result NULLIF(LENGTH(first_name), LENGTH(last_name)) result NULLIF(LENGTH(first_name), LENGTH(last_name)) result NULLIF(LENGTH(first_name), LENGTH(last_name)) resultFROM employees;FROM employees;FROM employees;FROM employees;

Using the Using the Using the Using the NULLIFNULLIFNULLIFNULLIF Function Function Function Function

…………

1111

22223333

1111 2222 3333

Page 47: Lesson03 学会使用单行函数

3-47 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Using the Using the Using the Using the COALESCECOALESCECOALESCECOALESCE Function Function Function Function

• The advantage of the The advantage of the The advantage of the The advantage of the COALESCECOALESCECOALESCECOALESCE function over the function over the function over the function over the NVLNVLNVLNVL function is that the function is that the function is that the function is that the COALESCECOALESCECOALESCECOALESCE function can function can function can function can take multiple alternate values.take multiple alternate values.take multiple alternate values.take multiple alternate values.

• If the first expression is not null, the If the first expression is not null, the If the first expression is not null, the If the first expression is not null, the COALESCECOALESCECOALESCECOALESCE function returns that expression; otherwise, it function returns that expression; otherwise, it function returns that expression; otherwise, it function returns that expression; otherwise, it does a does a does a does a COALESCECOALESCECOALESCECOALESCE of the remaining expressions. of the remaining expressions. of the remaining expressions. of the remaining expressions.

Page 48: Lesson03 学会使用单行函数

3-48 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, SELECT last_name, SELECT last_name, SELECT last_name, COALESCE(manager_id,commission_pct, -1) comm COALESCE(manager_id,commission_pct, -1) comm COALESCE(manager_id,commission_pct, -1) comm COALESCE(manager_id,commission_pct, -1) comm FROM employees FROM employees FROM employees FROM employees ORDER BY commission_pct; ORDER BY commission_pct; ORDER BY commission_pct; ORDER BY commission_pct;

Using the Using the Using the Using the COALESCECOALESCECOALESCECOALESCE Function Function Function Function

…………

Page 49: Lesson03 学会使用单行函数

3-49 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Conditional ExpressionsConditional ExpressionsConditional ExpressionsConditional Expressions

• Provide the use of IF-THEN-ELSE logic within a Provide the use of IF-THEN-ELSE logic within a Provide the use of IF-THEN-ELSE logic within a Provide the use of IF-THEN-ELSE logic within a SQL statementSQL statementSQL statementSQL statement

• Use two methods:Use two methods:Use two methods:Use two methods:– CASECASECASECASE expression expression expression expression– DECODEDECODEDECODEDECODE function function function function

Page 50: Lesson03 学会使用单行函数

3-50 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

CASECASECASECASE Expression Expression Expression Expression

Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement:an IF-THEN-ELSE statement:an IF-THEN-ELSE statement:an IF-THEN-ELSE statement:

CASE CASE CASE CASE exprexprexprexpr WHEN WHEN WHEN WHEN comparison_expr1comparison_expr1comparison_expr1comparison_expr1 THEN THEN THEN THEN return_expr1return_expr1return_expr1return_expr1 [WHEN[WHEN[WHEN[WHEN comparison_expr2 comparison_expr2 comparison_expr2 comparison_expr2 THENTHENTHENTHEN return_expr2 return_expr2 return_expr2 return_expr2 WHEN WHEN WHEN WHEN comparison_exprn comparison_exprn comparison_exprn comparison_exprn THENTHENTHENTHEN return_exprn return_exprn return_exprn return_exprn ELSE ELSE ELSE ELSE else_exprelse_exprelse_exprelse_expr]]]]ENDENDENDEND

Page 51: Lesson03 学会使用单行函数

3-51 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, job_id, salary,SELECT last_name, job_id, salary,SELECT last_name, job_id, salary,SELECT last_name, job_id, salary, CASE job_id WHEN 'IT_PROG' THEN 1.10 CASE job_id WHEN 'IT_PROG' THEN 1.10 CASE job_id WHEN 'IT_PROG' THEN 1.10 CASE job_id WHEN 'IT_PROG' THEN 1.10****salarysalarysalarysalary WHEN 'ST_CLERK' THEN 1.15 WHEN 'ST_CLERK' THEN 1.15 WHEN 'ST_CLERK' THEN 1.15 WHEN 'ST_CLERK' THEN 1.15****salarysalarysalarysalary WHEN 'SA_REP' THEN 1.20 WHEN 'SA_REP' THEN 1.20 WHEN 'SA_REP' THEN 1.20 WHEN 'SA_REP' THEN 1.20****salarysalarysalarysalary ELSE salary END "REVISED_SALARY" ELSE salary END "REVISED_SALARY" ELSE salary END "REVISED_SALARY" ELSE salary END "REVISED_SALARY"FROM employees;FROM employees;FROM employees;FROM employees;

Using the Using the Using the Using the CASECASECASECASE Expression Expression Expression Expression

Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement:an IF-THEN-ELSE statement:an IF-THEN-ELSE statement:an IF-THEN-ELSE statement:

…………

…………

Page 52: Lesson03 学会使用单行函数

3-52 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, job_id, salary,SELECT last_name, job_id, salary,SELECT last_name, job_id, salary,SELECT last_name, job_id, salary,hire_date,hire_date,hire_date,hire_date, CASE CASE CASE CASE WHEN WHEN WHEN WHEN months_between(sysdate,hire_date)/12>=20months_between(sysdate,hire_date)/12>=20months_between(sysdate,hire_date)/12>=20months_between(sysdate,hire_date)/12>=20 THEN THEN THEN THEN 2.002.002.002.00****salarysalarysalarysalary WHEN WHEN WHEN WHEN job_id in (job_id in (job_id in (job_id in ('ST_CLERK''ST_CLERK''ST_CLERK''ST_CLERK',,,,'SA_REP'SA_REP'SA_REP'SA_REP')')')') THEN 1.15THEN 1.15THEN 1.15THEN 1.15****salarysalarysalarysalary WHEN WHEN WHEN WHEN salary<=5000salary<=5000salary<=5000salary<=5000 THEN 1.20 THEN 1.20 THEN 1.20 THEN 1.20****salarysalarysalarysalary ELSE salary END "REVISED_SALARY"ELSE salary END "REVISED_SALARY"ELSE salary END "REVISED_SALARY"ELSE salary END "REVISED_SALARY"FROM employees;FROM employees;FROM employees;FROM employees;

Using the Using the Using the Using the CASECASECASECASE Expression Expression Expression Expression

Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of an IF-THEN-ELSE statement:an IF-THEN-ELSE statement:an IF-THEN-ELSE statement:an IF-THEN-ELSE statement:

Page 53: Lesson03 学会使用单行函数

3-53 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

DECODEDECODEDECODEDECODE Function Function Function Function

Facilitates conditional inquiries by doing the work of a Facilitates conditional inquiries by doing the work of a Facilitates conditional inquiries by doing the work of a Facilitates conditional inquiries by doing the work of a CASECASECASECASE expression or an IF-THEN-ELSE statement: expression or an IF-THEN-ELSE statement: expression or an IF-THEN-ELSE statement: expression or an IF-THEN-ELSE statement:

DECODE(DECODE(DECODE(DECODE(col|expression, search1, result1 col|expression, search1, result1 col|expression, search1, result1 col|expression, search1, result1 [[[[, search2, result2,...,, search2, result2,...,, search2, result2,...,, search2, result2,...,]]]] [[[[, default, default, default, default])])])])

Page 54: Lesson03 学会使用单行函数

3-54 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, job_id, salary,SELECT last_name, job_id, salary,SELECT last_name, job_id, salary,SELECT last_name, job_id, salary, DECODE(job_id, 'IT_PROG', 1.10 DECODE(job_id, 'IT_PROG', 1.10 DECODE(job_id, 'IT_PROG', 1.10 DECODE(job_id, 'IT_PROG', 1.10****salary,salary,salary,salary, 'ST_CLERK', 1.15 'ST_CLERK', 1.15 'ST_CLERK', 1.15 'ST_CLERK', 1.15****salary,salary,salary,salary, 'SA_REP', 1.20 'SA_REP', 1.20 'SA_REP', 1.20 'SA_REP', 1.20****salary,salary,salary,salary, salary) salary) salary) salary) REVISED_SALARY REVISED_SALARY REVISED_SALARY REVISED_SALARYFROM employees;FROM employees;FROM employees;FROM employees;

Using the Using the Using the Using the DECODEDECODEDECODEDECODE Function Function Function Function

…………

…………

Page 55: Lesson03 学会使用单行函数

3-55 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SELECT last_name, salary,SELECT last_name, salary,SELECT last_name, salary,SELECT last_name, salary, DECODE (TRUNC(salary/2000, 0), DECODE (TRUNC(salary/2000, 0), DECODE (TRUNC(salary/2000, 0), DECODE (TRUNC(salary/2000, 0), 0, 0.00, 0, 0.00, 0, 0.00, 0, 0.00, 1, 0.09, 1, 0.09, 1, 0.09, 1, 0.09, 2, 0.20, 2, 0.20, 2, 0.20, 2, 0.20, 3, 0.30, 3, 0.30, 3, 0.30, 3, 0.30, 4, 0.40, 4, 0.40, 4, 0.40, 4, 0.40, 5, 0.42, 5, 0.42, 5, 0.42, 5, 0.42, 6, 0.44, 6, 0.44, 6, 0.44, 6, 0.44, 0.45) TAX_RATE 0.45) TAX_RATE 0.45) TAX_RATE 0.45) TAX_RATEFROM employeesFROM employeesFROM employeesFROM employeesWHERE department_id = 80;WHERE department_id = 80;WHERE department_id = 80;WHERE department_id = 80;

Using the Using the Using the Using the DECODEDECODEDECODEDECODE Function Function Function Function

Display the applicable tax rate for each employee in Display the applicable tax rate for each employee in Display the applicable tax rate for each employee in Display the applicable tax rate for each employee in department 80:department 80:department 80:department 80:

Page 56: Lesson03 学会使用单行函数

3-56 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

SummarySummarySummarySummary

In this lesson, you should have learned how to: In this lesson, you should have learned how to: In this lesson, you should have learned how to: In this lesson, you should have learned how to: • Perform calculations on data using functionsPerform calculations on data using functionsPerform calculations on data using functionsPerform calculations on data using functions• Modify individual data items using functionsModify individual data items using functionsModify individual data items using functionsModify individual data items using functions• Manipulate output for groups of rows using Manipulate output for groups of rows using Manipulate output for groups of rows using Manipulate output for groups of rows using

functionsfunctionsfunctionsfunctions• Alter date formats for display using functionsAlter date formats for display using functionsAlter date formats for display using functionsAlter date formats for display using functions• Convert column data types using functionsConvert column data types using functionsConvert column data types using functionsConvert column data types using functions• Use Use Use Use NVLNVLNVLNVL functions functions functions functions• Use IF-THEN-ELSE logicUse IF-THEN-ELSE logicUse IF-THEN-ELSE logicUse IF-THEN-ELSE logic

Page 57: Lesson03 学会使用单行函数

3-57 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3: Overview of Part 2Practice 3: Overview of Part 2Practice 3: Overview of Part 2Practice 3: Overview of Part 2

This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:• Creating queries that require the use of numeric, Creating queries that require the use of numeric, Creating queries that require the use of numeric, Creating queries that require the use of numeric,

character, and date functionscharacter, and date functionscharacter, and date functionscharacter, and date functions• Using concatenation with functionsUsing concatenation with functionsUsing concatenation with functionsUsing concatenation with functions• Writing case-insensitive queries to test the Writing case-insensitive queries to test the Writing case-insensitive queries to test the Writing case-insensitive queries to test the

usefulness of character functionsusefulness of character functionsusefulness of character functionsusefulness of character functions• Performing calculations of years and months of Performing calculations of years and months of Performing calculations of years and months of Performing calculations of years and months of

service for an employeeservice for an employeeservice for an employeeservice for an employee• Determining the review date for an employeeDetermining the review date for an employeeDetermining the review date for an employeeDetermining the review date for an employee

Page 58: Lesson03 学会使用单行函数

3-58 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

Q1:Q1:Q1:Q1: Which two are character manipulation functions? Which two are character manipulation functions? Which two are character manipulation functions? Which two are character manipulation functions? (Choose two.) (Choose two.) (Choose two.) (Choose two.) AAAA. TRIM . TRIM . TRIM . TRIM BBBB. REPLACE . REPLACE . REPLACE . REPLACE C. TRUNC C. TRUNC C. TRUNC C. TRUNC D. TO_DATE D. TO_DATE D. TO_DATE D. TO_DATE E. MOD E. MOD E. MOD E. MOD F. CASE F. CASE F. CASE F. CASE

Page 59: Lesson03 学会使用单行函数

3-59 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

Q2:Q2:Q2:Q2:The CUSTOMERS table has these columns: The CUSTOMERS table has these columns: The CUSTOMERS table has these columns: The CUSTOMERS table has these columns: CUSTOMER_ID NUMBER(4) NOT NULL CUSTOMER_ID NUMBER(4) NOT NULL CUSTOMER_ID NUMBER(4) NOT NULL CUSTOMER_ID NUMBER(4) NOT NULL CUSTOMER_NAME VARCHAR2(100) NOT NULL CUSTOMER_NAME VARCHAR2(100) NOT NULL CUSTOMER_NAME VARCHAR2(100) NOT NULL CUSTOMER_NAME VARCHAR2(100) NOT NULL STREET_ADDRESS VARCHAR2(150) STREET_ADDRESS VARCHAR2(150) STREET_ADDRESS VARCHAR2(150) STREET_ADDRESS VARCHAR2(150) CITY_ADDRESS VARCHAR2(50) CITY_ADDRESS VARCHAR2(50) CITY_ADDRESS VARCHAR2(50) CITY_ADDRESS VARCHAR2(50) STATE_ADDRESS VARCHAR2(50) STATE_ADDRESS VARCHAR2(50) STATE_ADDRESS VARCHAR2(50) STATE_ADDRESS VARCHAR2(50) PROVINCE_ADDRESS VARCHAR2(50) PROVINCE_ADDRESS VARCHAR2(50) PROVINCE_ADDRESS VARCHAR2(50) PROVINCE_ADDRESS VARCHAR2(50) COUNTRY_ADDRESS VARCHAR2(50) COUNTRY_ADDRESS VARCHAR2(50) COUNTRY_ADDRESS VARCHAR2(50) COUNTRY_ADDRESS VARCHAR2(50) POSTAL_CODE VARCHAR2(12) POSTAL_CODE VARCHAR2(12) POSTAL_CODE VARCHAR2(12) POSTAL_CODE VARCHAR2(12) CUSTOMER_PHONE VARCHAR2(20) CUSTOMER_PHONE VARCHAR2(20) CUSTOMER_PHONE VARCHAR2(20) CUSTOMER_PHONE VARCHAR2(20)

Page 60: Lesson03 学会使用单行函数

3-60 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

Q2:Q2:Q2:Q2:A promotional sale is being advertised to the A promotional sale is being advertised to the A promotional sale is being advertised to the A promotional sale is being advertised to the customers in France. Which WHERE clause customers in France. Which WHERE clause customers in France. Which WHERE clause customers in France. Which WHERE clause identifies customers that are located in France? identifies customers that are located in France? identifies customers that are located in France? identifies customers that are located in France? A. WHERE lower(country_address) = "france" A. WHERE lower(country_address) = "france" A. WHERE lower(country_address) = "france" A. WHERE lower(country_address) = "france" BBBB. WHERE lower(country_address) = 'france' . WHERE lower(country_address) = 'france' . WHERE lower(country_address) = 'france' . WHERE lower(country_address) = 'france' C. WHERE lower(country_address) IS 'france' C. WHERE lower(country_address) IS 'france' C. WHERE lower(country_address) IS 'france' C. WHERE lower(country_address) IS 'france' D. WHERE lower(country_address) = '%france%' D. WHERE lower(country_address) = '%france%' D. WHERE lower(country_address) = '%france%' D. WHERE lower(country_address) = '%france%' E. WHERE lower(country_address) LIKE E. WHERE lower(country_address) LIKE E. WHERE lower(country_address) LIKE E. WHERE lower(country_address) LIKE %france% %france% %france% %france%

Page 61: Lesson03 学会使用单行函数

3-61 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

Q3: Q3: Q3: Q3: Which SELECT statement will get the result Which SELECT statement will get the result Which SELECT statement will get the result Which SELECT statement will get the result 'elloworld' from the string 'HelloWorld'? 'elloworld' from the string 'HelloWorld'? 'elloworld' from the string 'HelloWorld'? 'elloworld' from the string 'HelloWorld'?

A. SELECT SUBSTR( 'HelloWorld',1) FROM dual; A. SELECT SUBSTR( 'HelloWorld',1) FROM dual; A. SELECT SUBSTR( 'HelloWorld',1) FROM dual; A. SELECT SUBSTR( 'HelloWorld',1) FROM dual; B. SELECT INITCAP(TRIM ('HelloWorld', 1,1)) B. SELECT INITCAP(TRIM ('HelloWorld', 1,1)) B. SELECT INITCAP(TRIM ('HelloWorld', 1,1)) B. SELECT INITCAP(TRIM ('HelloWorld', 1,1)) FROM dual; FROM dual; FROM dual; FROM dual; C. SELECT LOWER(SUBSTR('HelloWorld', 1, 1) C. SELECT LOWER(SUBSTR('HelloWorld', 1, 1) C. SELECT LOWER(SUBSTR('HelloWorld', 1, 1) C. SELECT LOWER(SUBSTR('HelloWorld', 1, 1) FROM dual; FROM dual; FROM dual; FROM dual; D. SELECT LOWER(SUBSTR('HelloWorld', 2, 1) D. SELECT LOWER(SUBSTR('HelloWorld', 2, 1) D. SELECT LOWER(SUBSTR('HelloWorld', 2, 1) D. SELECT LOWER(SUBSTR('HelloWorld', 2, 1) FROM dual; FROM dual; FROM dual; FROM dual; EEEE. SELECT LOWER(TRIM ('H' FROM . SELECT LOWER(TRIM ('H' FROM . SELECT LOWER(TRIM ('H' FROM . SELECT LOWER(TRIM ('H' FROM 'HelloWorld')) FROM dual; 'HelloWorld')) FROM dual; 'HelloWorld')) FROM dual; 'HelloWorld')) FROM dual;

Page 62: Lesson03 学会使用单行函数

3-62 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

Q4:Q4:Q4:Q4:Evaluate the SQL statement:Evaluate the SQL statement:Evaluate the SQL statement:Evaluate the SQL statement:SELECT LPAD(salary,10,SELECT LPAD(salary,10,SELECT LPAD(salary,10,SELECT LPAD(salary,10,****) FROM EMP ) FROM EMP ) FROM EMP ) FROM EMP WHERE EMP_ID = 1001; WHERE EMP_ID = 1001; WHERE EMP_ID = 1001; WHERE EMP_ID = 1001;

If the employee with the EMP_ID 1001 has a salary If the employee with the EMP_ID 1001 has a salary If the employee with the EMP_ID 1001 has a salary If the employee with the EMP_ID 1001 has a salary of 17000, what is displayed? of 17000, what is displayed? of 17000, what is displayed? of 17000, what is displayed? A. 17000.00 A. 17000.00 A. 17000.00 A. 17000.00 B. 17000B. 17000B. 17000B. 17000******************** C. C. C. C. ****************170.00 170.00 170.00 170.00 D. D. D. D. ********17000.00 17000.00 17000.00 17000.00 EEEE. an error statement. an error statement. an error statement. an error statement

Page 63: Lesson03 学会使用单行函数

3-63 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

Q5:Q5:Q5:Q5:Evaluate the SQL statement:Evaluate the SQL statement:Evaluate the SQL statement:Evaluate the SQL statement:SELECT ROUND(TRUNC(MOD(1600,10),-1),2) SELECT ROUND(TRUNC(MOD(1600,10),-1),2) SELECT ROUND(TRUNC(MOD(1600,10),-1),2) SELECT ROUND(TRUNC(MOD(1600,10),-1),2) FROM dual; FROM dual; FROM dual; FROM dual;

WWWWhat hat hat hat will bewill bewill bewill be displayed? displayed? displayed? displayed? A. 0 A. 0 A. 0 A. 0 B. 1 B. 1 B. 1 B. 1 C. 0.00 C. 0.00 C. 0.00 C. 0.00 DDDD. . . . an error statement an error statement an error statement an error statement

Page 64: Lesson03 学会使用单行函数

3-64 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

Q6:Q6:Q6:Q6:Which SELECT statement should you use to Which SELECT statement should you use to Which SELECT statement should you use to Which SELECT statement should you use to extract the year from the system date and display it in extract the year from the system date and display it in extract the year from the system date and display it in extract the year from the system date and display it in the format "1998"? the format "1998"? the format "1998"? the format "1998"?

AAAA. SELECT TO_CHAR(SYSDATE,'yyyy') FROM dual; . SELECT TO_CHAR(SYSDATE,'yyyy') FROM dual; . SELECT TO_CHAR(SYSDATE,'yyyy') FROM dual; . SELECT TO_CHAR(SYSDATE,'yyyy') FROM dual; B. SELECT TO_DATE(SYSDATE,'yyyy') FROM dual; B. SELECT TO_DATE(SYSDATE,'yyyy') FROM dual; B. SELECT TO_DATE(SYSDATE,'yyyy') FROM dual; B. SELECT TO_DATE(SYSDATE,'yyyy') FROM dual; C. SELECT DECODE(SUBSTR(SYSDATE, 8), 'YYYY') C. SELECT DECODE(SUBSTR(SYSDATE, 8), 'YYYY') C. SELECT DECODE(SUBSTR(SYSDATE, 8), 'YYYY') C. SELECT DECODE(SUBSTR(SYSDATE, 8), 'YYYY') FROM dual; FROM dual; FROM dual; FROM dual; D. SELECT DECODE(SUBSTR(SYSDATE, 8), 'year') D. SELECT DECODE(SUBSTR(SYSDATE, 8), 'year') D. SELECT DECODE(SUBSTR(SYSDATE, 8), 'year') D. SELECT DECODE(SUBSTR(SYSDATE, 8), 'year') FROM dual; FROM dual; FROM dual; FROM dual; E. SELECT TO_CHAR(SUBSTR(SYSDATE, E. SELECT TO_CHAR(SUBSTR(SYSDATE, E. SELECT TO_CHAR(SUBSTR(SYSDATE, E. SELECT TO_CHAR(SUBSTR(SYSDATE, 8,2),'yyyy') 8,2),'yyyy') 8,2),'yyyy') 8,2),'yyyy') FROM dual; FROM dual; FROM dual; FROM dual;

Page 65: Lesson03 学会使用单行函数

3-65 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

Q7:Q7:Q7:Q7:Which three SELECT statements display 2000 in Which three SELECT statements display 2000 in Which three SELECT statements display 2000 in Which three SELECT statements display 2000 in the format "$2,000.00"?the format "$2,000.00"?the format "$2,000.00"?the format "$2,000.00"?

A. SELECT TO_CHAR(2000, '$#,###.##') FROM dual; A. SELECT TO_CHAR(2000, '$#,###.##') FROM dual; A. SELECT TO_CHAR(2000, '$#,###.##') FROM dual; A. SELECT TO_CHAR(2000, '$#,###.##') FROM dual; BBBB. SELECT TO_CHAR(2000, '$0,000.00') FROM dual; . SELECT TO_CHAR(2000, '$0,000.00') FROM dual; . SELECT TO_CHAR(2000, '$0,000.00') FROM dual; . SELECT TO_CHAR(2000, '$0,000.00') FROM dual; CCCC. SELECT TO_CHAR(2000, '$9,999.00') FROM dual; . SELECT TO_CHAR(2000, '$9,999.00') FROM dual; . SELECT TO_CHAR(2000, '$9,999.00') FROM dual; . SELECT TO_CHAR(2000, '$9,999.00') FROM dual; DDDD. SELECT TO_CHAR(2000, '$9,999.99') FROM dual; . SELECT TO_CHAR(2000, '$9,999.99') FROM dual; . SELECT TO_CHAR(2000, '$9,999.99') FROM dual; . SELECT TO_CHAR(2000, '$9,999.99') FROM dual; E. SELECT TO_CHAR(2000, '$2,000.00') FROM dual; E. SELECT TO_CHAR(2000, '$2,000.00') FROM dual; E. SELECT TO_CHAR(2000, '$2,000.00') FROM dual; E. SELECT TO_CHAR(2000, '$2,000.00') FROM dual; F. SELECT TO_CHAR(2000, '$N,NNN.NN') FROM F. SELECT TO_CHAR(2000, '$N,NNN.NN') FROM F. SELECT TO_CHAR(2000, '$N,NNN.NN') FROM F. SELECT TO_CHAR(2000, '$N,NNN.NN') FROM dual;dual;dual;dual;

Page 66: Lesson03 学会使用单行函数

3-66 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

Q8:Q8:Q8:Q8:Which SQL statement displays the date March 19, Which SQL statement displays the date March 19, Which SQL statement displays the date March 19, Which SQL statement displays the date March 19, 2001 in a format that appears as "Nineteenth of March 2001 in a format that appears as "Nineteenth of March 2001 in a format that appears as "Nineteenth of March 2001 in a format that appears as "Nineteenth of March 2001 12:00:00 AM"? 2001 12:00:00 AM"? 2001 12:00:00 AM"? 2001 12:00:00 AM"?

AAAA. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-Mon-YYYY'), 'fmDdspth "of" Month YYYY fmHH:MI:SS Mon-YYYY'), 'fmDdspth "of" Month YYYY fmHH:MI:SS Mon-YYYY'), 'fmDdspth "of" Month YYYY fmHH:MI:SS Mon-YYYY'), 'fmDdspth "of" Month YYYY fmHH:MI:SS AM')AM')AM')AM') NEW_DATE FROM dual; NEW_DATE FROM dual; NEW_DATE FROM dual; NEW_DATE FROM dual;

B. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-B. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-B. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-B. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-Mon-YYYY'), 'Ddspth "of" Month YYYY fmHH:MI:SS Mon-YYYY'), 'Ddspth "of" Month YYYY fmHH:MI:SS Mon-YYYY'), 'Ddspth "of" Month YYYY fmHH:MI:SS Mon-YYYY'), 'Ddspth "of" Month YYYY fmHH:MI:SS AM') NEW_DATE FROM dual; AM') NEW_DATE FROM dual; AM') NEW_DATE FROM dual; AM') NEW_DATE FROM dual;

Page 67: Lesson03 学会使用单行函数

3-67 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. All rights reserved.

Practice 3Practice 3Practice 3Practice 3

C. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-C. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-C. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-C. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-Mon-YYYY'), 'fmDdspth "of" Month YYYY HH:MI:SS Mon-YYYY'), 'fmDdspth "of" Month YYYY HH:MI:SS Mon-YYYY'), 'fmDdspth "of" Month YYYY HH:MI:SS Mon-YYYY'), 'fmDdspth "of" Month YYYY HH:MI:SS AM')AM')AM')AM') NEW_DATE FROM dual; NEW_DATE FROM dual; NEW_DATE FROM dual; NEW_DATE FROM dual;

D. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-D. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-D. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-D. SELECT TO_CHAR(TO_DATE('19-Mar-2001', 'DD-Mon-YYYY'), 'fmtDdspth "of" Month YYYY Mon-YYYY'), 'fmtDdspth "of" Month YYYY Mon-YYYY'), 'fmtDdspth "of" Month YYYY Mon-YYYY'), 'fmtDdspth "of" Month YYYY fmfmfmfmtHH:MI:SS AM') NEW_DATE FROM dual; tHH:MI:SS AM') NEW_DATE FROM dual; tHH:MI:SS AM') NEW_DATE FROM dual; tHH:MI:SS AM') NEW_DATE FROM dual;