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

Tài liệu OCA: Oracle Database 11g Administrator Certified Associate Study Guide- P6 pdf

50 414 0

Đ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

Định dạng
Số trang 50
Dung lượng 650,3 KB

Nội dung

Utilizing Aggregate Functions 181 F single 47 M single 92 married 180 F married 63 M married 117 More DBA Queries In the “Exploring DBA Queries Using Aggregate Functions” sidebar, you saw some que- ries written to find out the space allocated by tablespace, the space allocated by schema, and the space allocated by tablespace and schema. These were written using three dif- ferent SQL statements. You can see the power of CUBE in the following SQL. The results from all the three SQL statements you tried before are in this summary report, showing the different levels of aggregation. SELECT tablespace_name, owner, SUM(bytes)/1048576 size_mb FROM dba_segments GROUP BY CUBE (tablespace_name, owner); TABLESPACE_NAME OWNER SIZE_MB ----------------- --------------- ---------- 1564.8125 <- Grand Total HR 1.75 <- Subtotal HR schema IX 1.625 <- Subtotal IX schema OE 8.875 … … … FLOWS 100.6875 <- Subtotal FLOWS schema USERS 21.25 <- Subtotal USERS tablespace USERS HR .1875 <- HR schema in USERS tablespace USERS OE 2.625 <- OE schema in USERS tablespace USERS SH 2 USERS SCOTT .375 USERS BTHOMAS 16.0625 SYSAUX 716.375 <- Subtotal SYSAUX tablespace … … … SYSAUX FLOWS 100.6875 SYSTEM 701.625 <- Subtotal SYSTEM tablespace SYSTEM SYS 685.1875 95127c03.indd 181 2/17/09 11:38:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 182 Chapter 3 N Using Group Functions SYSTEM OUTLN .5625 SYSTEM SYSTEM 15.875 EXAMPLE 77.3125 EXAMPLE HR 1.5625 … … … As you can see in the result, the space used by each schema in each tablespace is shown as well as the total space used in each tablespace and the total space used by each schema. The total space used in the database (including all tablespaces) is also shown in the very first line. Three functions come in handy with the ROLLUP and CUBE modifiers of the GROUP BY clause— GROUPING , GROUP_ID , and GROUPING_ID . In the examples you have seen using the ROLLUP and CUBE modifiers, there was no way of telling which row is a subtotal and which row is a grand total. You can use the GROUPING function to overcome this problem. Review the following SQL example: SELECT gender, marital_status, count(*) num_rec, GROUPING (gender) g_grp, GROUPING (marital_status) ms_grp FROM oe.customers GROUP BY CUBE(marital_status, gender); G MARITAL_STATUS NUM_REC G_GRP MS_GRP - -------------------- ---------- ---------- ---------- 319 1 1 F 110 0 1 M 209 0 1 single 139 1 0 F single 47 0 0 M single 92 0 0 married 180 1 0 F married 63 0 0 M married 117 0 0 The G_GRP column has a 1 for NULL values generated by the CUBE or ROLLUP modifier for GENDER column. Similarly, the MS_GRP column has a 1 when NULL values are generated in the MARITAL_STATUS column. Using a DECODE function on the result of the GROUPING function, you can produce a more meaningful result set, as in the following example: SELECT DECODE(GROUPING (gender), 1, ‘Multi-Gender’, gender) gender, DECODE(GROUPING (marital_status), 1, 95127c03.indd 182 2/17/09 11:38:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Utilizing Aggregate Functions 183 ‘Multi-MaritalStatus’, marital_status) marital_status, count(*) num_rec FROM oe.customers GROUP BY CUBE(marital_status, gender); GENDER MARITAL_STATUS NUM_REC ------------ -------------------- ---------- Multi-Gender Multi-MaritalStatus 319 F Multi-MaritalStatus 110 M Multi-MaritalStatus 209 Multi-Gender single 139 F single 47 M single 92 Multi-Gender married 180 F married 63 M married 117 You can use the GROUPING function in the HAVING clause to filter out rows. You can display only the summary results using the GROUPING function in the HAVING clause. The GROUPING_ID function returns the exact level of the group. It is derived from the GROUPING function by concatenating the GROUPING levels together as bits, and gives the GROUPING_ID . Review the following example closely to understand this: SELECT gender, marital_status, count(*) num_rec, GROUPING (gender) g_grp, GROUPING (marital_status) ms_grp, GROUPING_ID (gender, marital_status) groupingid FROM oe.customers GROUP BY CUBE(gender, marital_status); G MARITAL_STATUS NUM_REC G_GRP MS_GRP GROUPINGID - -------------------- ---------- ---------- ---------- ---------- 319 1 1 3 single 139 1 0 2 married 180 1 0 2 F 110 0 1 1 F single 47 0 0 0 F married 63 0 0 0 M 209 0 1 1 M single 92 0 0 0 M married 117 0 0 0 95127c03.indd 183 2/17/09 11:38:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 184 Chapter 3 N Using Group Functions In this example, you can clearly identify the level of grouping using the GROUPING_ID function. The GROUP_ID function is used to distinguish the duplicate groups. In the follow- ing example, the GROUP_ID() value is 1 for duplicate groups. When writing complex aggre- gates, you can filter out the duplicate rows by using the HAVING GROUP_ID = 0 clause in the SELECT statement. SELECT gender, marital_status, count(*) num_rec, GROUPING_ID (gender, marital_status) groupingid, GROUP_ID() groupid FROM oe.customers GROUP BY gender, CUBE(gender, marital_status); G MARITAL_STATUS NUM_REC GROUPINGID GROUPID - -------------------- ---------- ---------- ---------- F single 47 0 0 F married 63 0 0 M single 92 0 0 M married 117 0 0 F single 47 0 1 F married 63 0 1 M single 92 0 1 M married 117 0 1 F 110 1 0 M 209 1 0 F 110 1 1 M 209 1 1 Nesting Functions Functions can be nested so that the output from one function is used as input to another. Operators have an inherent precedence of execution such as * before + , but function precedence is based on position only. Functions are evaluated innermost to outermost and left to right. This nesting technique is common with some functions, such as DECODE (covered in Chapter 2), where it can be used to implement limited IF…THEN…ELSE logic within a SQL statement. For example, the V$SYSSTAT view contains one row for each of three interesting sort statistics. If you want to report all three statistics on a single line, you can use DECODE com- bined with SUM to filter out data in the SELECT clause. This filtering operation is usually done in the WHERE or HAVING clause, but if you want all three statistics on one line, you can issue this command: SELECT SUM (DECODE (name,’sorts (memory)’,value,0)) in_memory, 95127c03.indd 184 2/17/09 11:38:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Utilizing Aggregate Functions 185 SUM (DECODE (name,’sorts (disk)’, value,0)) on_disk, SUM (DECODE (name,’sorts (rows)’, value,0)) rows_sorted FROM v$sysstat; IN_MEMORY ON_DISK ROWS_SORTED --------- ------- ----------- 728 12 326714 What happens in the previous statement is a single pass through the V$SYSSTAT table. The presummary result set would have the same number of rows as V$SYSSTAT (232, for instance). Of these 232 rows, all rows and columns have zeros, except for one row in each column that has the data of interest. Table 3.3 shows the data that was used in this example. The summation operation then adds all the zeros to your interesting data and gives you the results you want. TABLE 3.3 Presummarized Result Set in_memory on_disk rows_sorted 0 0 0 0 12 0 0 0 0 0 0 326714 728 0 0 0 0 0 Nesting Single-Row Functions with Group Functions Nested functions can include single-row functions nested within group functions, as you’ve just seen, or group functions nested within either single-row functions or other group func- tions. For example, suppose you need to report on the departments in the EMP table, show- ing either the number of jobs or the number of managers, whichever is greater. You would enter the following: SELECT deptno, GREATEST( COUNT(DISTINCT job), COUNT(DISTINCT mgr)) cnt, COUNT(DISTINCT job) jobs, 95127c03.indd 185 2/17/09 11:38:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 186 Chapter 3 N Using Group Functions COUNT(DISTINCT mgr) mgrs FROM scott.emp GROUP BY deptno; DEPTNO CNT JOBS MGRS ---------- ---------- ---------- ---------- 10 3 3 2 20 4 3 4 30 3 3 2 Nesting Group Functions You can also nest group functions within group functions. Only one level of nesting is allowed when nesting a group function within a group function. To report the maximum number of jobs in a single department, you would query the following: SELECT MAX(COUNT (DISTINCT job_id)) FROM employees GROUP BY department_id; MAX(COUNT(DISTINCTJOB_ID)) -------------------------- 3 Group functions can be nested only one level. If you try to nest more than one level of nested group functions, you will encounter an error. Also, there is no reason to do so. Here is an example to show the error, though the SQL does not mean much: SELECT MIN (MAX (COUNT (DISTINCT job_id))) FROM employees GROUP BY department_id; SELECT MIN (MAX (COUNT (DISTINCT job_id))) * ERROR at line 1: ORA-00935: group function is nested too deeply 95127c03.indd 186 2/17/09 11:38:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Exam Essentials 187 Summary Though this chapter is small in terms of OCA certification exam content, this chapter is very important for the test. It is important to understand the concept of grouping data, where GROUP BY and HAVING clauses can be used, and the rules associated with using these clauses. I started this chapter by discussing the group-function fundamentals and reviewed the group functions by concentrating on the functions that are important for the test. I also discussed how group functions can be used in the SELECT , HAVING , and ORDER BY clauses of SELECT statements. Most group functions can be applied to all data values or only to the distinct data values. Except for COUNT(*) , group functions ignore NULL s. Pro- grammer-written functions cannot be used as group functions. COUNT , SUM , and AVG are the most commonly used group functions. When using group functions or aggregate functions in a query, the columns that do not have any aggregate function applied to them must appear in the GROUP BY clause of the query. The HAVING clause is used to filter out data after the aggregates are calculated. Group func- tions cannot be used in the WHERE clause. You can create superaggregates using the CUBE and ROLLUP modifiers in the GROUP BY clause. Exam Essentials Understand the usage of DISTINCT in group functions. When DISTINCT is specified, only one of each non- NULL value is applied to the function. To apply all non- NULL values, the keyword ALL should be used. Know where group functions can be used. Group functions can be used in GROUP BY , ORDER BY , and HAVING clauses. They cannot be used in WHERE clauses. Know how MIN and MAX sort date and character data. Older dates evaluate to lower values, while newer dates evaluate to higher values. Character data, even if it contains numbers, is sorted according to the NLS_SORT specification. Know which expressions in a SELECT list must appear in a GROUP BY clause. If any group- ing is performed, all nongroup function expressions and nonconstant expressions must appear in the GROUP BY clause. Know the order of precedence for evaluating nested functions. You may need to evalu- ate an expression containing nested functions. Make sure you understand the left-to-right order of precedence used to evaluate these expressions. 95127c03.indd 187 2/17/09 11:38:12 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 188 Review Questions Review Questions 1. How will the results of the following two statements differ? Statement 1: SELECT MAX(longitude), MAX(latitude) FROM zip_state_city; Statement 2: SELECT MAX(longitude), MAX(latitude) FROM zip_state_city GROUP BY state; A. Statement 1 will fail because it is missing a GROUP BY clause. B. Statement 2 will return one row, and statement 1 may return more than one row. C. Statement 2 will fail because it does not have the columns used in the GROUP BY clause in the SELECT clause. D. Statement 1 will display two columns, and statement 2 will display two values for each state. 2. Using the SALES table described here, you need to report the following: Gross, net, and earned revenue for the second and third quarters of 1999 ÛN Gross, net, and earned revenue for sales in the states of Illinois, California, and ÛN Texas (codes IL , CA , and TX ) Column Name state_code sales_date gross net earned Key Type PK PK Nulls/Unique NN NN NN NN NN FK Table Datatype VARCHAR2 DATE NUMBER NUMBER NUMBER Length 2 11,2 11,2 11,2 Will all the requirements be met with the following SQL statement? SELECT state_code, SUM(ALL gross), SUM(net), SUM(earned) FROM sales_detail WHERE TRUNC(sales_date,’Q’) BETWEEN TO_DATE(’01-Apr-1999’,’DD-Mon-YYYY’) AND TO_DATE(’01-Sep-1999’,’DD-Mon-YYYY’) AND state_cd IN (’IL’,’CA’,’TX’) GROUP BY state_code; 95127c03.indd 188 2/17/09 11:38:13 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Review Questions 189 A. The statement meets all three requirements. B. The statement meets two of the three requirements. C. The statement meets one of the three requirements. D. The statement meets none of the three requirements. E. The statement will raise an exception. 3. Which line in the following SQL has an error? 1 SELECT department_id, SUM(salary) 2 FROM employees 3 WHERE department_id <> 40 4 ORDER BY department_id; A. 1 B. 3 C. 4 D. No errors in SQL 4. John is trying to find out the average salary of employees in each department. He noticed that the SALARY column can have NULL values, and he does not want the NULLs included when calculating the average. Identify the correct SQL that will produce the desired results. A. SELECT department_id, AVG(salary) FROM employees GROUP BY department_id; B. SELECT department_id, AVG(NVL(salary,0)) FROM employees GROUP BY department_id; C. SELECT department_id, NVL(AVG(salary), 0) FROM employees GROUP BY department_id; D. SELECT department_id, AVG(salary) FROM employees GROUP BY department_id HAVING salary IS NOT NULL; 95127c03.indd 189 2/17/09 11:38:13 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 190 Review Questions 5. Review the following two SQL statements, and choose the appropriate option. 1. SELECT department_id, COUNT(*) FROM employees HAVING COUNT(*) > 10 GROUP BY department_id; 2. SELECT department_id, COUNT(*) FROM employees WHERE COUNT(*) > 10 GROUP BY department_id; A. Statement 1 and statement 2 will produce the same results. B. Statement 1 will succeed, and statement 2 will fail. C. Statement 2 will succeed, and statement 1 will fail. D. Both statements fail. 6. Read the following SQL carefully, and choose the appropriate option. The JOB_ID column shows the various jobs. SELECT MAX(COUNT(*)) FROM employees GROUP BY job_id, department_id; A. Aggregate functions cannot be nested. B. The columns in the GROUP BY clause must appear in the SELECT clause for the query to work. C. The GROUP BY clause is not required in this query. D. The SQL will produce the highest number of jobs within a department. 7. Identify the SQL that produces the correct result. A. SELECT department_id, SUM(salary) FROM employees WHERE department_id <> 50 GROUP BY department_id HAVING COUNT(*) > 30; B. SELECT department_id, SUM(salary) sum_sal FROM employees WHERE department_id <> 50 GROUP BY department_id HAVING sum_sal > 3000; 95127c03.indd 190 2/17/09 11:38:13 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... you must qualify the column name with the table name or table alias To execute a join of three or more tables, Oracle takes these steps: 1 Oracle joins two of the tables based on the join conditions, comparing their columns 2 Oracle joins the result to another table, based on join conditions 3 Oracle continues this process until all tables are joined into the result 200  Chapter 4    Using Joins and... syntax, for the certification exam Set operators in Oracle let you combine results from two or more SELECT statements The results of each SELECT statement are considered a set, and Oracle provides UNION, INTERSECT, and MINUS operators to get the desired results You will learn how these operators work in this chapter Writing Multiple-Table Queries In relational database management systems (RDBMSs), related... can also specify the relationship using a JOIN clause instead of the WHERE clause The JOIN clause introduced by Oracle in Oracle 9i was then added to conform to the ISO/ANSI Writing Multiple-Table Queries  199 SQL1999 standard Throughout this section, you’ll see examples of queries using the Oracle native syntax as well as the ISO/ANSI SQL1999 standard A query from multiple tables without a relationship... summarized 20 C.  The GROUP BY and HAVING clauses can appear in any order in the SELECT clause If a WHERE clause is present, it must be before the GROUP BY clause Chapter 4 Using Joins and Subqueries Oracle Database 11g: SQL Fundamentals I exam objectives covered in this chapter ÛÛ Displaying data from multiple tables NN Write SELECT statements to access data from more than one table using equijoins and nonequijoins... NN Control the order of rows returned A database has many tables that store data In Chapter 1, “Introducing SQL,” you learned how to write simple queries that select data from one table Although this information is essential to passing the certification exam, the ability to join two or more related tables and access information is the core strength of relational databases Using the SELECT statement,... department_name locations l, departments d l.location_id = d.location_id country_id != ‘US’; When tables (or views or materialized views) are specified in the FROM clause, Oracle looks for the object in the schema (or user) connected to the database If the table belongs to another schema, you must qualify it with the schema name (You may avoid this by using synonyms, which are discussed in Chapter 7, “Creating... clauses If there are no common column names between the two tables used in the join (the FROM clause), you don’t need to qualify the columns However, if you qualify the columns, you are telling the Oracle database engine where exactly to find the column; hence, you are improving the performance of the query If there are column names common to multiple tables used in a join query, you must qualify the... different, Oracle tries to perform an implicit datatype conversion This may affect your query performance It is better if the columns used in the join condition have the same datatype or if you use the explicit conversion functions you learned in Chapter 2, “Using SingleRow Functions.” 202  Chapter 4    Using Joins and Subqueries n Using the ANSI Syntax The difference between traditional Oracle join... you do not use parentheses, Oracle uses left associativity by pairing the tables from left to right (as in the first scenario) By using parentheses, you can make the query less ambiguous, as shown here: SELECT region_id, region_name, country_id, country_name, location_id, city FROM locations NATURAL JOIN (regions NATURAL JOIN countries); The same query written in traditional Oracle syntax is as follows:... you might want to see the data from one table, even if there is no corresponding row in the joining table Oracle provides the outer join mechanism for this An outer join returns results based on the inner join condition, as well as the unmatched rows from one or both of the tables In traditional Oracle syntax, the plus symbol surrounded by parentheses, (+), denotes an outer join in the query Enter (+) . AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 4 Using Joins and Subqueries ORACLE DATABASE 11g: SQL FUNDAMENTALS. introduced by Oracle in Oracle 9i was then added to conform to the ISO/ANSI 95127c04.indd 198 2/18/09 9:43:34 AM Please purchase PDF Split-Merge on www.verypdf.com

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

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN