1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu OCA: Oracle Database 11g Administrator Certified Associate- P5 ppt

50 418 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Using Other Single-Row Functions
Trường học Oracle University
Chuyên ngành Database Administration
Thể loại Tài liệu
Định dạng
Số trang 50
Dung lượng 633,44 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The basic syntax of using a group function in the SELECT statement is as follows: SELECT [column names], group_function column_name, … … …FROM table [WHERE condition] [GROUP BY column na

Trang 1

Using Other Single-Row Functions 131

BG_JOB_ID Returns the job ID (that is, DBA_JOBS) if the session was created

by a background process Returns NULL if the session is a ground session See also FG_JOB_ID

fore-CLIENT_IDENTIFIER Returns the client session identifier in the global context It can

be set with the DBMS_SESSION built-in package

CLIENT_INFO Returns the 64 bytes of user session information stored by

DBMS_APPLICATION_INFO.CURRENT_BIND Returns bind variables for fine-grained auditing

CURRENT_SCHEMA Returns the current schema as set by ALTER SESSION SET

CURRENT_SCHEMA or, by default, the login schema/ID

CURRENT_SCHEMAID Returns the numeric ID for CURRENT_SCHEMA.CURRENT_SQL Returns the SQL that triggered fine-grained auditing (use only

within scope inside the event handler for fine-grained auditing)

CURRENT_SQL_LENGTH Returns the length of the current SQL that triggered

fine-grained auditing

DB_DOMAIN Returns the contents of the DB_DOMAINinit.ora parameter

DB_NAME Returns the contents of the DB_NAMEinit.ora parameter

DB_UNIQUE_NAME Returns the contents of the DB_UNIQUE_NAMEinit.ora

parameter

ENTRYID Returns the auditing entry identifier ENTERPRISE_IDENTITY Returns OID DN for enterprise users, for local users NULL

FG_JOB_ID Returns the job ID of the current session if a foreground

pro-cess created it Returns NULL if the session is a background session See also BG_JOB_ID

GLOBAL_CONTEXT_MEMORY Returns the number in the SGA by the globally accessible

context

GLOBAL_UID Returns the global user ID from OID

HOST Returns the hostname of the machine from where the client

connected This is not the same terminal in V$SESSION

ta b l e 2 14 Parameters in the USERENV Namespace (continued)

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Trang 2

132 Chapter 2 N Using Single-Row Functions

IDENTIFICATION_TYPE Returns how the user is set to authenticate in the database:

LOCAL, EXTERNAL, or GLOBAL

INSTANCE Returns the instance number for the instance to which the

session is connected This is always 1 unless you are running Oracle Real Application Clusters

INSTANCE_NAME Returns the name of the instance

IP_ADDRESS Returns the IP address of the machine from where the client

connected

ISDBA Returns TRUE if the user connected AS SYSDBA LANG Returns the ISO abbreviation for the language name

LANGUAGE Returns a character string containing the language and

terri-tory used by the session and the database character set in the form language_territory.characterset.

MODULE Returns the application name set through

DBMS_APPLICATION_INFO.NETWORK_PROTOCOL Returns the network protocol being used as specified in the

PROTOCOL= section of the connect string or tnsnames.ora definition

NLS_CALENDAR Returns the calendar for the current session

NLS_CURRENCY Returns the currency for the current session

NLS_DATE_FORMAT Returns the date format for the current session

NLS_DATE_LANGUAGE Returns the language used for displaying dates

NLS_SORT Returns the binary or linguistic sort basis

NLS_TERRITORY Returns the territory for the current session

OS_USER Returns the operating-system username for the current session

POLICY_INVOKER Returns the invoker of row-level security-policy functions

Returns OID DN when the proxy user is an enterprise user

ta b l e 2 14 Parameters in the USERENV Namespace (continued)

Trang 3

Using Other Single-Row Functions 133

PROXY_GOLBAL_UID Returns the global user ID from OID for Enterprise User

Secu-rity proxy users

PROXY_USER Returns the name of the database user who opened the current

session for the session user

PROXY_USERID Returns the numeric ID for the database user who opened the

current session for the session user

SERVER_HOST Returns the hostname of the machine where the instance is

running

SERVICE_NAME Returns the name of the service where the session is connected

SESSION_USER Returns the database username for the current session

SESSION_USERID Returns the numeric database user ID for the current session

SESSIONID Returns the auditing session identifier AUDSID This parameter

is out of scope for distributed queries

SID Returns the session number (same as the SID from

V$SESSION)

STATEMENT_ID Returns the auditing statement identifier

TERMINAL Returns the terminal identifier for the current session This is

the same as the terminal in V$SESSION

Here are few more examples of SYS_CONTEXT in the USERENV namespace:

SELECT SYS_CONTEXT(‘USERENV’, ‘OS_USER’), SYS_CONTEXT(‘USERENV’, ‘CURRENT_SCHEMA’), SYS_CONTEXT(‘USERENV’, ‘HOST’),

SYS_CONTEXT(‘USERENV’, ‘NLS_TERRITORY’)FROM dual;

SYS_CONTEXT(‘USERENV’,’OS_USER’)SYS_CONTEXT(‘USERENV’,’CURRENT_SCHEMA’)SYS_CONTEXT(‘USERENV’,’HOST’)

SYS_CONTEXT(‘USERENV’,’NLS_TERRITORY’) -

ta b l e 2 14 Parameters in the USERENV Namespace (continued)

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Trang 4

134 Chapter 2 N Using Single-Row Functions

oracleHRlinux04.mycompany.corpAMERICA

SYS_GUID

SYS_GUID() generates a globally unique identifier as a RAW value This function is useful for creating a unique identifier to identify a row SYS_GUID() returns a 32-bit hexadecimal representation of the 16-byte RAW value

SELECT SYS_GUID() FROM DUAL;

SYS_GUID() -CDA78A020D6E43A6AB743A5CE8CB8C55

SELECT SYS_GUID() FROM DUAL;

SYS_GUID() -DC7C19A3AD264CE184C64194E65F83E5

UID

UID takes no parameters and returns the integer user ID for the current user connected to the session The user ID uniquely identifies each user in a database and can be selected from the DBA_USERS view

SQL> SHOW USERUSER is “BTHOMAS”

SELECT username, account_statusFROM dba_users

WHERE user_id = UID;

USERNAME ACCOUNT_STATUS - -BTHOMAS OPEN

Trang 5

Using Other Single-Row Functions 135

N returns the instance identifier to which the session is connected This option

is useful only if you are running the Oracle Parallel Server and have multiple instances

LANGUAGE

Û

N returns the language, territory, and database character set The delimiters are

an underscore (_) between language and territory and a period (.) between the tory and character set

The option can appear in uppercase, lowercase, or mixed case The USERENV function

has been deprecated since Oracle 9i It is recommended to use the SYS_CONTEXT function

with the built-in USERENV namespace instead

VSIZE

VSIZE(x) takes a single argument, where x is an expression This function returns the size

in bytes of the internal representation of the x.SELECT last_name, first_name,

VSIZE(last_name) ln_size, VSIZE(first_name) fn_sizeFROM employees

WHERE last_name like ‘K%’;

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Trang 6

LAST_NAME FIRST_NAME LN_SIZE FN_SIZE

-Kaufling Payam 8 5

Khoo Alexander 4 9

King Janette 4 7

King Steven 4 6

Kochhar Neena 7 5

Kumar Sundita 5 7 Since the database character set is single-byte, the byte used for each character is 1;

hence, the size shown here is actually the number of characters in the input For multibyte characters, this would be different

Summary

This chapter introduced single-row functions It started by discussing the functions

avail-able in Oracle 11g to handle NULLs Then it discussed the single-row functions availavail-able in Oracle 11g by grouping them into character, numeric, date, and conversion functions.

You learned that single-row functions return a value for each row as it is retrieved from the table You can use single-row functions to interpret NULL values, format output, convert datatypes, transform data, perform date arithmetic, give environment information, and perform trigonometric calculations

You can use single-row functions in the SELECT, WHERE, and ORDER BY clauses of SELECT statements I covered the rich assortment of functions available in each datatype category and some functions that work on any datatype

The NVL, NVL2, and COALESCE functions interpret NULL values

The single-row character functions operate on character input The INSTR function returns the position of a substring within the string The SUBSTR function returns a portion of the string INSTR and SUBSTR are great for extracting part of the input string REPLACE and TRANSLATE transform the input

Single-row numeric functions operate on numeric input FLOOR, CEIL, ROUND, and TRUNC get the nearest number FLOOR, CEIL, and ROUND return the nearest integer, whereas ROUND returns a value rounded to certain digits of precision REMAINDER and MOD are similar functions

Date functions operate on datetime values SYSDATE and SYSTIMESTAMP values return the current date and time MONTHS_BETWEEN finds the number of months between two date val-ues ADD_MONTHS is a commonly used function and can add months to or subtract months from a date You can use ROUND and TRUNC on datetime values to find the nearest date, month, or year

Of the conversion functions, TO_CHAR and TO_DATE are the most commonly used I also reviewed the format codes that can be used with numeric and datetime values

Trang 7

137

Exam Essentials

Understand where single-row functions can be used Single-row functions can be used in

the SELECT, WHERE, and ORDER BY clauses of SELECT statements

Know the effects that NULL values can have on arithmetic and other functions Any

arith-metic operation on a NULL results in a NULL This is true of most functions as well Use the NVL, NVL2, and COALESCE functions to deal with NULLs

Review the character-manipulation functions Understand the arguments and the result

of using character-manipulation functions such as INSTR, SUBSTR, REPLACE, and TRANSLATE

Understand the numeric functions Know the effects of using TRUNC and ROUND with -n as the second argument Also practice using LENGTH and INSTR, which return a numeric result, inside SUBSTR and other character functions

Know how date arithmetic works When adding or subtracting numeric values from a

DATE datatype, whole numbers represent days Also, the date/time intervals INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND can be added or subtracted from date/time datatypes You need to know how to interpret and create expressions that add intervals to

or subtract intervals from dates

Know the datatypes for the various date/time functions Oracle has many date/time

func-tions to support the date/time datatypes You need to know the return datatypes for these functions SYSDATE and CURRENT_DATE return a DATE datatype CURRENT_TIMESTAMP and SYSTIMESTAMP return a TIMESTAMP WITH TIME ZONE datatype LOCALTIMESTAMP returns a TIMESTAMP datatype

Know the format models for converting dates to/from character strings In practice, you

can simply look up format codes in a reference For the certification exam, you must have them memorized

Understand the use of the DECODE function DECODE acts like a case statement in C, Pascal,

or Ada Learn how this function works and how to use it

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Trang 8

138 Review Questions

Review Questions

1 You want to display each project’s start date as the day, week, number, and year Which

statement will give output like the following?

Tuesday Week 23, 2008

A SELECT proj_id, TO_CHAR(start_date, ‘DOW Week WOY YYYY’) FROM projects;

B SELECT proj_id, TO_CHAR(start_date,’Day’||’ Week’||’ WOY, YYYY’) FROM

projects;

C SELECT proj_id, TO_CHAR(start_date, ‘Day” Week” WW, YYYY’) FROM projects;

D SELECT proj_id, TO_CHAR(start_date, ‘Day Week# , YYYY’) FROM projects;

E You can’t calculate week numbers with Oracle.

2 What will the following statement return?

SELECT last_name, first_name, start_dateFROM employees

WHERE hire_date < TRUNC(SYSDATE) – 5;

A Employees hired within the past five hours

B Employees hired within the past five days

C Employees hired more than five hours ago

D Employees hired more than five days ago

3 Which assertion about the following statements is most true?

SELECT name, region_code||phone_numberFROM customers;

SELECT name, CONCAT(region_code,phone_number)FROM customers;

A If REGION_CODE is NULL, the first statement will not include that customer’s PHONE_

NUMBER

B If REGION_CODE is NULL, the second statement will not include that customer’s PHONE_

NUMBER

C Both statements will return the same data.

D The second statement will raise an error if REGION_CODE is NULL for any customer.

4 Which single-row function could you use to return a specific portion of a character string?

A INSTR

B SUBSTR

C LPAD

Trang 9

Review Questions 139

5 The data in the PRODUCT table is as described here The bonus amount is calculated as the

lesser of 5 percent of the base price or 20 percent of the surcharge

Which of the following statements will achieve the desired results?

A SELECT sku, name, LEAST(base_price * 1.05, surcharge * 1.2)

D A, B, and C will all achieve the desired results.

E None of these statements will achieve the desired results.

6 Which function(s) accept arguments of any datatype? (Choose all that apply.)

Trang 10

140 Review Questions

8 The SALARY table has the following data:

LAST_NAME FIRST_NAME SALARY

-Mavris Susan 6500

Higgins Shelley 12000

Tobias Sigal Colmenares Karen 2500

Weiss Matthew 8000

Mourgos Kevin 5800

Rogers Michael 2900

Stiles Stephen 3200 Consider the following SQL, and choose the best option:

SELECT last_name, NVL2(salary, salary, 0) N1, NVL(salary,0) N2

FROM salary;

A Column N1 and N2 will have different results.

B Column N1 will show zero for all rows, and column N2 will show the correct salary

values, and zero for Tobias

C The SQL will error out because the number of arguments in the NVL2 function is

incorrect

D Columns N1 and N2 will show the same result.

9 Which two functions could you use to strip leading characters from a character string?

(Choose two.)

A LTRIM

B SUBSTR

C RTRIM

D INSTR

E STRIP

10 What is the result of MOD(x1, 4), if x1 is 11?

A –1

B 3

C 1

D REMAINDER(11,4)

Trang 11

Review Questions 141

11 Which two SQL statements will replace the last two characters of last_name with ‘XX‘ in

the employees table when executed? (Choose two.)

A SELECT RTRIM(last_name, SUBSTR(last_name, LENGTH(last_name)-1)) || ‘XX’

new_col FROM employees;

B SELECT REPLACE(last_name, SUBSTR(last_name, LENGTH(last_name)-1), ‘XX’)

new_col FROM employees;

C SELECT REPLACE(SUBSTR(last_name, LENGTH(last_name)-1), ‘XX’) new_col

FROM employees;

D SELECT CONCAT(SUBSTR(last_name, 1,LENGTH(last_name)-2), ‘XX’) new_col

FROM employees;

12 Which date components does the CURRENT_TIMESTAMP function display?

A Session date, session time, and session time zone offset

B Session date and session time

C Session date and session time zone offset

D Session time zone offset

13 Using the SALESPERSON_REVENUE table described here, which statements will properly

dis-play the TOTAL_REVENUE (CAR_SALES + WARRANTY_SALES) of each salesperson?

Column Name salesperson_id car_sales warranty_sales

B SELECT salesperson_id, car_sales, warranty_sales, car_sales +

NVL2(warranty_sales,0) total_sales FROM salesperson_revenue;

C SELECT salesperson_id, car_sales, warranty_sales, NVL2(warranty_sales,

car_sales + warranty_sales, car_sales) total_sales FROM salesperson_revenue;

D SELECT salesperson_id, car_sales, warranty_sales, car_sales +

COALESCE(car_sales, warranty_sales, car_sales + warranty_sales) total_

sales FROM salesperson_revenue;

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Trang 12

142 Review Questions

14 What will be the result of executing the following SQL, if today’s date is February 28, 2009?

SELECT ADD_MONTHS(‘28-FEB-09’, -12) from dual;

A 28-FEB-10

B 28-FEB-08

C 29-FEB-08

D 28-JAN-08

15 Consider the following two SQL statements, and choose the best option:

1 SELECT TO_DATE(‘30-SEP-07’,’DD-MM-YYYY’) from dual;

2 SELECT TO_DATE(‘30-SEP-07’,’DD-MON-RRRR’) from dual;

A Statement 1 will error; 2 will produce result.

B The resulting date value from the two statements will be the same.

C The resulting date value from the two statements will be different.

D Both statements will generate an error.

16 What will the following SQL statement return?

SELECT COALESCE(NULL,’Oracle ‘,’Certified’) FROM dual;

E None of the above

18 Which function will return a TIMESTAMP WITH TIME ZONE datatype?

A CURRENT_TIMESTAMP

B LOCALTIMESTAMP

C CURRENT_DATE

D SYSDATE

Trang 13

Review Questions 143

19 Which statement would change all occurrences of the string ‘IBM’ to the string ’SUN’ in

the DESCRIPTION column of the VENDOR table?

A SELECT TRANSLATE(description, ‘IBM’, ‘SUN’) FROM vendor

B SELECT CONVERT(description, ‘IBM’, ‘SUN’) FROM vendor

C SELECT EXTRACT(description, ‘IBM’, ‘SUN’) FROM vendor

D SELECT REPLACE(description, ‘IBM’, ‘SUN’) FROM vendor

20 Which function implements IF…THEN…ELSE logic?

Trang 14

144 Answers to Review Questions

Answers to Review Questions

1 C Double quotation marks must surround literal strings like ”Week”.

2 D The TRUNC function removes the time portion of a date by default, and whole numbers

added to or subtracted from dates represent days added or subtracted from that date

TRUNC(SYSDATE) –5 means five days ago at midnight

3 C The two statements are equivalent.

4 B SUBSTR returns part of the string INSTR returns a number LPAD adds to a character

string LEAST does not change an input string

5 C Options A and B do not account for NULL surcharges correctly and will set the bonus

to NULL where the surcharge is NULL In option B, the NVL function is applied to the base_

price column instead of the surcharge column In option C, the LEAST function will return a NULL if surcharge is NULL, in which case BASE_PRICE * 1.05 would be returned from the COALESCE function

6 B, D ROUND does not accept character arguments SUBSTR accepts only character

argu-ments SIGN accepts only numeric arguargu-ments

7 A The functions are evaluated from the innermost to outermost, as follows:

SIGN(ABS(NVL(-32,0))) = SIGN(ABS(-32)) = SIGN(32) = 1

8 D The NVL function returns zero if the salary value is NULL, or else it returns the original

value The NVL2 function returns the second argument if the salary value is not NULL If NULL, the third argument is returned

9 A, B RTRIM removes trailing (not leading) characters INSTR returns a number STRIP is not

a valid Oracle function SUBSTR with second argument greater than 1 removes leading acters from a string

char-10 B MOD returns the number remainder after division The REMAINDER function is similar to

MOD but will use the ROUND function in the algorithm; hence, the result of REMAINDER(11,4) would be –1 MOD uses FLOOR in the algorithm

11 A, D The SUBSTR function in option A would return the last two characters of the last

name These two characters are right-trimmed using the RTRIM function The result would

be the first portion of the last name and is concatenated to ‘XX’ Option B also would do the same as A, but would replace all the occurrences of the last two characters (Paululul will be PaXXXXXX instead of PaululXX) Option C would return only the last two characters

of the last name The SUBSTR function in option D would return the first character through the last –2 characters ‘XX‘ is concatenated to the result

12 A The CURRENT_TIMESTAMP function returns the session date, session time, and session

time zone offset The return datatype is TIMESTAMP WITH TIME ZONE

Trang 15

Answers to Review Questions 145

13 C Option A will result in NULL TOTAL_SALES for rows where there are NULL WARRANTY_

SALES Option B is not the correct syntax for NVL2, because it requires three arguments

With option C, if WARRANTY_SALES is NULL, then CAR_SALES is returned; otherwise, CAR_

SALES+WARRANTY_SALES is returned The COALESCE function returns the first non-NULL argument and could be used to obtain the desired results, but the first argument here is CAR_SALES, which is not NULL, and therefore COALESCE will always return CAR_SALES

14 C The ADD_MONTHS function returns the date d plus i months If <d> is the last day of the month

or the resulting month has fewer days, then the result is the last day of the resulting month

15 C Statement 1 will result in 30-SEP-0007, and statement 2 will result in 30-SEP-2007

The RR and RRRR formats derive the century based on the current date if the century is not specified The YY format will use the current century, and the YYYY format expects the cen-tury in the input

16 B The COALESCE function returns the first non-NULL parameter, which is the character

string ‘Oracle ‘

17 E Option A will not work if there is a February 29 (leap year) in the next 365 days Option

B will always add one year to the present date, except if the current date is February 29 (leap year) Option C will return the date one day later NEW_TIME is used to return the date/time in a different time zone ADD_MONTHS (SYSDATE,12) can be used to achieve the desired result

18 A LOCALTIMESTAMP does not return the time zone CURRENT_DATE and SYSDATE return

nei-ther fractional seconds nor a time zone; they both return the DATE datatype

19 D CONVERT is used to change from one character set to another EXTRACT works on date/

time datatypes TRANSLATE changes all occurrences of each character with a positionally corresponding character, so ‘I like IBM’ would become ‘S like SUN’

20 C The INITCAP function capitalizes the first letter in each word The REPLACE function

performs search-and-replace string operations There is no IFELSE function The DECODE function is the one that implements IF…THEN…ELSE logic

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Trang 17

NDescribe the use of group functionsÛ

NGroup data by using the GROUP BY clauseÛ

NInclude or exclude the grouped rows by using the Û

NHAVING clause

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Trang 18

As explained in the previous chapter, functions are programs

that take zero or more arguments and return a single value The exam focuses on two types of functions: single-row and aggre-gate (group) functions Single-row functions were covered in Chapter 2, “Using Single-Row Functions.” Group functions are covered in this chapter

Group functions differ from single-row functions in how they are evaluated Single-row functions are evaluated once for each row retrieved Group functions are evaluated on groups of one or more rows at a time

In this chapter, you will explore which group functions are available in SQL, the rules for how to use them, and what to expect on the exam about aggregating data and group functions You will also explore nesting function calls together SQL allows you to nest group functions within calls to single-row functions, as well as nest single-row functions within calls to group functions

Group-Function Fundamentals

Group functions are sometimes called aggregate functions and return a value based on a

num-ber of inputs The exact numnum-ber of inputs is not determined until the query is executed and all rows are fetched This differs from single-row functions, in which the number of inputs is known at parse time—before the query is executed Because of this difference, group functions have slightly different requirements and behavior than single-row functions

Group functions do not consider NULL values, except the COUNT(*) and GROUPING functions

You may apply the NVL function to the argument of the group function to substitute a value for NULL and hence be included in the processing of the group function If the dataset contains all NULL values or there are no rows in the dataset, the group function returns NULL (the only exception to this rule is COUNT—it returns zero)

Most of the group functions can be applied either to ALL values or to only the DISTINCT values for the specified expression When ALL is specified, all non-NULL values are applied to the group function When DISTINCT is specified, only one of each non-NULL value is applied

to the function If you do not specify ALL or DISTINCT, the default is ALL

To better understand the difference of ALL vs DISTINCT, let’s look at a few rows from the EMPLOYEES table:

SELECT first_name, salary

Trang 19

Utilizing Aggregate Functions 149

FIRST_NAME SALARY

-Donald 2600

Douglas 2600

Diana 4200

David 4800

David 6800

Daniel 9000

David 9500

Danielle 9500

Den 11000

The SALARY column contains nine values Two employees have 2,600 and 9,500 each When you count unique entries in the SALARY column, there are seven, since two are duplicates The following SQL shows a few examples The COUNT function is used to get a count, and the SUM function is used to find the total (I’ll discuss these functions later in the chapter.) When the UNIQUE keyword is used, the 2,600 and 9,500 are included in the result only once SELECT COUNT(salary) cnt_nu, COUNT(DISTINCT salary) cnt_uq, SUM(salary) sum_nu, SUM(DISTINCT salary) sum_uq FROM employees WHERE first_name LIKE ‘D%’; CNT_NU CNT_UQ SUM_NU SUM_UQ

9 7 60000 47900

Unlike with single-row functions, you cannot use programmer-written functions on grouped data

Utilizing Aggregate Functions

As with single-row functions, Oracle offers a rich variety of aggregate functions These functions can appear in the SELECT, ORDER BY, or HAVING clauses of SELECT statements

When used in the SELECT clause, they usually require a GROUP BY clause as well If no GROUP

BY clause is specified, the default grouping is for the entire result set Group functions can-not appear in the WHERE clause of a SELECT statement The GROUP BY and HAVING clauses of SELECT statements are associated with grouping data I’ll discuss the GROUP BY clause before you learn about the various group functions

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Trang 20

150 Chapter 3 N Using Group Functions

You almost certainly will encounter a certification-exam question that tests whether you will incorrectly put a group function in the WHERE clause

Grouping Data with GROUP BY

As the name implies, group functions work on data that is grouped You tell the database how to group or categorize the data with a GROUP BY clause Whenever you use a group func-tion in the SELECT clause of a SELECT statement, you must place all nongrouping/nonconstant columns in the GROUP BY clause If no GROUP BY clause is specified (only group functions and constants appear in the SELECT clause), the default grouping becomes the entire result set

When the query executes and the data is fetched, it is grouped based on the GROUP BY clause, and the group function is applied

The basic syntax of using a group function in the SELECT statement is as follows:

SELECT [column names], group_function (column_name), … … …FROM table

[WHERE condition]

[GROUP BY column names]

[ORDER BY column names]

In the following example, you find the total number of employees from the EMPLOYEES table:

SELECT COUNT(*) FROM employees;

COUNT(*) - 107Since you did not have any other column in the SELECT clause, you didn’t need to specify the GROUP BY clause Suppose you want to find out the number of employees in each depart-ment; you can include department_id in the SELECT clause:

SELECT department_id, COUNT(*) “#Employees”

FROM employees;

SELECT department_id, COUNT(*) “#Employees”

*ERROR at line 1:

ORA-00937: not a single-group group functionSince you used an aggregate function and nonaggregated column, Oracle gave an error and is telling you to group the data Here you have to use the GROUP BY clause If you include

Trang 21

Utilizing Aggregate Functions 151

a group function in the SELECT clause, you cannot select individual results unless you use the GROUP BY clause Make sure all the columns in the SELECT clause that are not part of a group function are included in the GROUP BY clause The following SQL lists the number of employ-ees by their department:

SELECT department_id, COUNT(*) “#Employees”

FROM employees GROUP BY department_id;

DEPARTMENT_ID #Employees

-

100 6

30 6

1

20 2

70 1

90 3

110 2

50 45

40 1

80 34

10 1

60 5 Notice that the rows are returned in no specific order If you want the rows to be arranged in the order of the number of employees, you can either specify the aggregate function in the ORDER BY clause or use the position of the column, like so:

SELECT department_id, COUNT(*) “#Employees”

FROM employees GROUP BY department_id ORDER BY count(*) DESC, department_id;

SELECT department_id, COUNT(*) “#Employees”

FROM employees GROUP BY department_id ORDER BY 2 DESC, department_id;

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Trang 22

152 Chapter 3 N Using Group Functions

DEPARTMENT_ID #Employees - -

BY clause and hence is giving an error:

SELECT department_id, COUNT(*) “#Employees”

FROM employeesGROUP BY 1;

SELECT department_id, COUNT(*) “#Employees”

*ERROR at line 1:

ORA-00979: not a GROUP BY expressionThe following is another invalid SQL statement In this example, the GROUP BY clause is using a column alias, which is not supported Pay particular attention to GROUP BY questions on the certification exam, because you might see one with a column alias or column position used

SELECT department_id di, COUNT(*) emp_cntFROM employees

GROUP BY di;

GROUP BY di *ERROR at line 3:

ORA-00904: “DI”: invalid identifierThe GROUP BY column does not have to be in the SELECT clause In most cases, the result may not make much sense, but you might need it In the following example, you are calculating the average salary of employees in each department; you do not want to share which department the average salary belongs to, and all you are interested in is knowing the average salaries in the company by department:

Trang 23

Utilizing Aggregate Functions 153

AVERAGE_SALARY - 8600 4420 7000 9500 10000 19333.3333 10150 3475.55556 6500 8955.88235 4400 5760

If you have more than one column in the GROUP BY clause, Oracle creates groups within groups The order of columns in the GROUP BY clause determines the grouping Multiple col-umns in the GROUP BY clause are required when you have more than one nonaggregate column

in the SELECT clause In the following example, the rows are grouped by the department_id, and within each department they are grouped by the job_id The SQL shows the number of different jobs within each department:

SELECT department_id, job_id, COUNT(*)FROM employees

GROUP BY department_id, job_idORDER BY 1, 2;

DEPARTMENT_ID JOB_ID COUNT(*) - - -

Trang 24

154 Chapter 3 N Using Group Functions

The GROUP BY clause groups data, but Oracle does not guarantee the order

of the result set by the grouping order To order the data in any specific order, you must use the ORDER BY clause

Group-Function Overview

Tables 3.1 and 3.2 summarize the group functions discussed in this chapter I will cover each of these functions in the “Group-Function Descriptions” sections Table 3.1 summa-rizes the group functions that are most likely to appear on the OCP certification exam

ta b l e 3 1 Group-Function Summary: Part 1

COUNT Returns the number of non-NULL rows

MEDIAN Returns a middle value

STDDEV Returns the standard deviation

VARIANCE Returns the sample variance, or 1 for sample size 1

Table 3.2 summarizes the group functions available in Oracle Database 11g that are not

included in Table 3.1 Although they are less likely to appear on the certification exam, they

Trang 25

Utilizing Aggregate Functions 155

ta b l e 3 2 Group-Function Summary: Part 2

CORR Returns the coefficient of correlation of number pairsCOVAR_POP Returns the population covariance of number pairsCOVAR_SAMP Returns the sample covariance of number pairsCUME_DIST Returns the cumulative distribution of values within groupingsDENSE_RANK Returns the ranking of rows within an ordered group, without

skipping ranks on tiesFIRST Modifies other aggregate functions to return expressions based

on the ordering of the second-column expressionGROUP_ID Returns a group identifier used to uniquely identify duplicate

groupsGROUPING Returns 0 for nonsummary rows or 1 for summary rowsGROUPING_ID Helps determine group by levels when CUBE or ROLLUP is used

KEEP Modifies other aggregate functions to return the first or last

value in a groupingLAST Modifies other aggregate functions to return expressions based

on ordering of the second-column expressionPERCENTILE_CONT Returns the interpolated value that would fall in the specified

percentile position using a continuous modelPERCENTILE_DISC Returns the interpolated value that would fall in the specified

percentile position using a discrete modelPERCENT_RANK Returns the percentile ranking of the specified value RANK Returns the ranking of rows within an ordered group, skipping

ranks when ties occurSTDDEV_POP Returns the population standard deviationSTDDEV_SAMP Returns the sample standard deviationVAR_POP Returns the population varianceVAR_SAMP Returns the sample variance

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Ngày đăng: 14/12/2013, 15:15

TỪ KHÓA LIÊN QUAN