ORACLE SQL Fundamental I 1-4 章重點 Chap 1 Introduction Chap 2 Retrieving Data Using the SQL...
-
Upload
warren-phillips -
Category
Documents
-
view
234 -
download
2
Transcript of ORACLE SQL Fundamental I 1-4 章重點 Chap 1 Introduction Chap 2 Retrieving Data Using the SQL...
ORACLE SQL Fundamental I
1-4 章重點Chap 1 IntroductionChap 2 Retrieving Data Using the SQL SELECT Statement
Chap 3 Restricting and Sorting DataChap 4 Using Single-Row Functions to Customize Output
軟體: Oracle DB 11g Enterprise
從 www.oracle.com下載 Oracle DB 11g Enterprise, 包含 HR 的資料 HR 資料用於範例說明及上機實習 安裝時
1. 下載的檔案要先解壓縮2. HR 的帳號要解鎖 , 且設密碼 (如 : hr 或 Oracle11g )
P.S. 1. Oracle DB 11g Express 2. Oracle DB 12c 為雲端的資料庫
2
第一種編輯軟體─ ─ SQLdeveloper 安裝 SQLdeveloper :
1. 從 www.oracle.com / downloads /developer tools 下載 2. 須先安裝 JDK ( 版本不要太新 , 1.6 版即可 )3. 進入 SQLdeveloper, 連線登入時需輸入 SID( 資料庫 )
1) orcl : 11g Enterprise2) xe : 11g Express
» 右鍵 /property/save 密碼
執行 SQLdeveloper :1. 先執行桌面的 『 Open Oracle Service 』2. 再執行桌面的 『 sqldeveloper 』3. 進入 SQLdeveloper 後,點選左邊視窗的 hr ,密碼輸入 hr
4
第二種編輯軟體─ ─ SQLPLUS
SQLPLUS :在『命令提示字元』 (DOS 環境 ) 直接下指令
C:>sqlplus hr/hrSQL> select * from hr.employees;SQL> select table_name from user_tables;…….. 離開 SQLPLUS …………….SQL> exit
或使用管理者進去C:>sqlplus sys/oracle as sysdbaSQL> alter user hr identified by hr account unlock;
5
1-23 Entity Relationship Model
實體間的關係 :Assign one or more employees to a department Some departments do not yet have assigned employees
屬性 :Mandatory( 強制 ) marked with 『 *』 ( 一定要輸入 )optional ( 選項 ) marked with 『 o』Primary( 主鍵 ) marked with 『 #』
8
15
2- 4 Retrieving Data Using the SQL SELECT Statement
Projection: Selects the columns in a table that are returned by a query
Selection: Selects the rows in a table that are returned by a query
Joins: Brings together data that is stored in different tables by specifying the
link between them
16
2-5
SELECT {*|[DISTINCT] column|expression [alias],...}FROM table;
* 選擇全部欄位
DISTINCT Suppresses duplicates 重複值只取一個 SQL 指令不分大小寫 (not case sensitive) SQL 指令以 ; (semicolon) 結束 , SQL*Plus 一定要加『 ;』
Run Script icon或 [F5] : ( 執行全部指令 ) run the command or commands in the SQL Worksheetexecutes all the statements in the Enter SQL Statement box
Execute Statement icon 或 press [F9] : ( 執行指標所指的指令 ) run a SQL statement in the SQL Worksheetexecutes the statement at the mouse pointer in the Enter SQL
Statement box
有 DISTINCT 時 , SELECT 只能列一個欄位
SQL Developer:標題( heading )預設靠左( Left-aligned )標題大寫 (Uppercase)
SELECT last_name, hire_date, salary
FROM employees;
SQL*Plus:標題( heading ):
字元 (Character) 和日期 (Date) 靠左( Left-aligned ) 數字 (Number) 靠右 (right-aligned)
標題大寫 (Uppercase)
17
2-9
18
2-11 Arithmetic Expressions (+, -, *, / ) 可用於:
數字 (Number)日期 (Date)
DATE 和 TIMESTAMP 只能用 + 和 -除了 From 子句Oracle Server 會忽略運算子前後的空白( blank spaces )
NULL 是 unavailable, unassigned, unknown, or inapplicable
NULL 不是 0 也不是空白 (blank space)
2-14
19
2-15SELECT last_name, 12*salary*commission_pct
FROM employees;
Arithmetic expressions containing a null value evaluate to nullnull 做運算 (+-*/) 後還是 null例如 :
除以 0(division by zero) 會產生錯誤 但,除以 null (divide a number by null), 結果還是 null 或
unknown
20
2-17
alias (別名) :緊接在欄位後可使用 AS若別名包含空白、特殊字元、大小寫
以「 " " 」雙引號 (double quotation marks) 括住 且有分大小寫
SELECT last_name "Name" , salary*12 "Annual Salary"
FROM employees;
p.s. 若 alias 沒以雙引號括住,則標頭列印時 , 為大寫
2-18
SELECT last_name AS name, commission_pct comm
FROM employees;
SELECT last_name "Name" , salary*12 "Annual Salary"
FROM employees;
21
補充 :106.View the Exhibit and examine the description of the EMPLOYEES table. Your company wants to give 5% bonus to all the employees on their annual salary. The SALARY column stores the monthly salary for an employee. To check the total for annual salary and bonus amount for each employee, you issued the following SQL statement: SELECT first_name, salary, salary*12+salary*12*.05 "ANNUAL SALARY + BONUS" FROM employees;
Which statement is true regarding the above query?
A. It would execute and give you the desired output.
B. It would not execute because the AS keyword is missing between the column
name and the alias.
C. It would not execute because double quotation marks are used instead of single
quotation marks for assigning alias for the third column.
D. It would execute but the result for the third column would be inaccurate because
the parentheses for overriding the precedence of the operator are missing.
Answer: A 22
題庫 106
公司要給所有員工年薪 5% 的獎金 ,SALARY 為月薪
別名 alias
別名之前的 AS 可省略
double quotation marks 雙引號是對的
這裡不加括弧(parentheses) 沒關係
23
2-20 Concatenation Operator (連接運算子):
two vertical bars (||)連接 columns 或 字串concatenate 字串和 null, 結果為字串
LAST_NAME || NULL 結果是 LAST_NAMEdate 型態也可以做 concatenate
Date 和 character literal values 必須包含在單引號 『 ' ' 』中SELECT last_name || ' is a ' || job_id
AS "Employee Details"
FROM employees;
2-21
24
2-23 Alternative Quote (q) Operator
指定自己的 quotation mark delimiter( 定義符號 )mark delimiter 可以是 single-byte or multibyte, or any of the
following character pairs: [ ], { }, ( ), or < >
SELECT department_name || q'[ Department's Manager Id: ]'
|| manager_id AS "Department and Manager"
FROM departments;
補充 :104.SELECT product_name || 'it's not available for order' FROM product_information WHERE product_status = 'obsolete'; You received the following error while executing the above query: ERROR: ORA-01756: quoted string not properly terminated What would you do to execute the query successfully?
A. Enclose the character literal string in the SELECT clause within the double
quotation marks.
B. Do not enclose the character literal string in the SELECT clause within the
single quotation marks.
C. Use Quote (q) operator and delimiter to allow the use of single quotation mark
in the literal character string.
D. Use escape character to negate the single quotation mark inside the literal
character string in the SELECT clause.
Answer: C 25
題庫 104
常數字串必須包含在單引號 ‘ 『 ’』中 , 但若常數字串本身已內含單引號 ,就要指定自己的 quotation mark delimiter
更正為 : SELECT product_name || q'[it's not available for order]' FROM product_information WHERE product_status = 'obsolete';
26
2-24
DISTINCT :去除重複值SELECT DISTINCT department_id
FROM employees;
不加 DISTINCT :SELECT department_id
FROM employees;
SELECT DISTINCT department_id, employee_idFROM employees; 沒有去除重複資料
去除重複資料
28
2-27
NUMBER(p,s)Number value having a maximum number of digits p, with s
digits to the right of the decimal point最長 p 位,小數 s 位
VARCHAR2(s)Variable-length character value of maximum size s變動長度字串,最長 s 位
30
3-6 Restricting and Sorting Data
SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE department_id = 90 ;
where 子句不可使用別名
31
3-7 數字常數:
不需要用單引號 字串:
為 case-sensitive ( 有分大小寫 ) 字串及日期值:
須用單引號括起來SELECT last_nameFROM employeesWHERE hire_date = '17-FEB-96' ; 錯誤 : 不是有效的月份查詢現在的日期及格式: select sysdate from dual;SELECT last_name,hire_dateFROM employeesWHERE hire_date = '07-6月 -02' ;
date 為 format-sensitive ( 有分日期格式 ) 預設 date 顯示格式為 DD-MON-RR
Alter session set nls_date_format =‘YYYY-MM-DD:HH24:MI:SS’;
Alter session set nls_date_language =American;
NLS : National Language Support
33
3-10
between 低 and 高包含最低和最高值且須先寫最低值可用於數字、字串SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 2500 AND 3500 ;
SELECT last_name
FROM employees
WHERE last_name BETWEEN 'King' AND 'Smith' ;
若改為 BETWEEN 3500 AND 2500語法沒有錯誤 , 但結果不對找不到資料
34
3-11
in (., ., .)括號內的值 , 不用按順序排列可用於任何型態oracle 內部是使用 or 來處理 in , 所以 , in 沒有效率優勢
SELECT employee_id, last_name, salary, manager_id
FROM employees
WHERE manager_id IN (100, 101, 201) ;
相當於 WHERE manager_id =100 or manager_id =101 or manager_id =201
35
3-12
LIKE萬用字元( wildcard )搜尋% : 0 或多個字元 _ :一個字元
SELECT first_name
FROM employees
WHERE first_name LIKE 'S%' ;
尋找 January, 2002 and December, 2002 期間進公司的員工SELECT last_name, hire_date
FROM employees
WHERE hire_date LIKE '%02' ;
36
3-13
% 和 _ 並用:SELECT last_name
FROM employees
WHERE last_name LIKE '_o%' ;若要找的字剛好是萬用字元 %或 _, 則需用 escape '\' 來識別
SELECT job_id
FROM jobs
WHERE job_id LIKE '%SA\_%' ESCAPE '\'
37
3-14 NULL Conditions :
WHERE 子句 要用 is null 不可以用 = null
SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NULL ;
SELECT last_name, manager_id
FROM employees
WHERE manager_id = NULL ;
SELECT last_name, manager_id
FROM employees
WHERE manager_id IS NOT NULL ;
語法沒有錯誤但結果不對找不到資料
38
3-16 AND Truth Table (強勢 : false > null > true )
TRUE AND NULL = NULLFALSE AND NULL = FALSENULL AND NULL = NULL
SELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary >= 10000AND job_id LIKE '%MAN%' ;
39
3-17 OR Truth Table (強勢 : true > null > false )
NULL or FALSE = NULLNULL or NULL = NULLNULL or TRUE = TRUE
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary >= 10000
OR job_id LIKE '%MAN%' ;
補充 :23.display PRODUCT_NAME from the table where the CATEGORY_ID column has values 12 or 13, and the SUPPLIER_ID column has the value 102088.SELECT product_name FROM product_information WHERE (category_id = 12 AND category_id = 13) AND supplier_id = 102088;
A. It would execute but the output would return no rows.
B. It would execute and the output would display the desired result.
C. It would not execute because the entire WHERE clause condition is
not enclosed within the parentheses.
D. It would not execute because the same column has been used in
both sides of the AND logical operator to form the condition.
Answer: A
40
題庫 23
查詢 CATEGORY_ID 欄位值 12 or 13 , 且SUPPLIER_ID 為 102088 的產品名稱(PRODUCT_NAME)
產品的類別 CATEGORY_ID 欄位值不可能既為 12 又為 13 , 所以查出來為 NULL 值
41
3-18
NOT... WHERE job_id NOT IN ('AC_ACCOUNT', 'AD_VP')
... WHERE salary NOT BETWEEN 10000 AND 15000
... WHERE last_name NOT LIKE '%A%'
... WHERE commission_pct IS NOT NULL
43
3-21SELECT last_name, job_id, salary
FROM employees
WHERE job_id = 'SA_REP'
OR job_id = 'AD_PRES'
AND salary > 15000;
SELECT last_name, job_id, salary
FROM employees
WHERE ( job_id = 'SA_REP'
OR job_id = 'AD_PRES' )
AND salary > 15000;
先做 AND , 再做 OR
用括弧 ,使 OR 先做 , 再做 AND
44
3-23 order by order by
排序 , 一定要在 select 敘述的最後 可以用別名
SELECT employee_id, last_name, salary*12 annsal
FROM employees
ORDER BY annsal
可以用運算式SELECT employee_id, last_name, salary*12 annsal
FROM employees
ORDER BY salary*12
若沒用 order by , 則每次輸出順序可能都不一樣ASC: Ascending ,預設由小到大,可省略DESC: Descending ,由大到小order by 的欄位 : 不用一定要出現在 select lists
Where 及 group by 不可用別名
3-24 order by
ASC : null 值放後頭select commission_pct
from employees
order by commission_pct ;
DESC: null 值放前頭 select commission_pct
from employees
order by commission_pct desc ;
45
補充 :7.the product names and the date of expiration of warranty for all the products, if the product is purchased today. The products that have no warranty should be displayed at the top and the products with maximum warranty period should be displayed at the bottom.
46
題庫 7
查詢產品名稱及保證到期日 , 假設產品今天購買 , 最大的產品保證到期日放在後面
補充 :7.(續 )
A. SELECT product_name,
SYSDATE+warranty_period AS "Warranty expire date"
FROM product_information
ORDER BY SYSDATE-warranty_period;
B. SELECT product_name,
SYSDATE+warranty_period AS "Warranty expire date"
FROM product_information
ORDER BY SYSDATE+warranty_period;
C. SELECT product_name,
SYSDATE+warranty_period AS "Warranty expire date"
FROM product_information
ORDER BY SYSDATE;
D. SELECT product_name,
SYSDATE+warranty_period "Warranty expire date"
FROM product_information
WHERE warranty_period > SYSDATE;
Answer: B 47
題庫 7
更正為 : ORDER BY SYSDATE+warranty_period;
更正為 : ORDER BY SYSDATE+warranty_period;
更正為 : ORDER BY SYSDATE+warranty_period;
48
3-24 order by 控制 null 順序 :
NULLS FIRST: 若有 row含 NULL 值 , 則放在最前面 select commission_pct
from employees
order by commission_pct nulls first ;
NULLS LAST: 若有 row含 NULL 值 , 則放在最後面select commission_pct
from employees
order by commission_pct desc nulls last ;
49
3-25 以欄位的數字位置( column’s numeric position )排序:
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY 3 ;
多個欄位排序SELECT last_name, department_id, salary
FROM employees
ORDER BY department_id, salary DESC;
亦即以 department_id 做排序
department_id 以 ASC 做排序salary以 DESC 做排序
補充 :70.SELECT product_name, list_price, min_price, list_price - min_price Difference FROM product_information
sorted output in ascending order of the price difference between LIST_PRICE and MIN_PRICE? (Choose all that apply.)
A. ORDER BY 4
B. ORDER BY MIN_PRICE
C. ORDER BY DIFFERENCE
D. ORDER BY LIST_PRICE
E. ORDER BY LIST_PRICE - MIN_PRICE
Answer: A C E 50
題庫 70
將 LIST_PRICE and MIN_PRICE 的 price difference ( 差額 ) 做升冪排序
補充 :58.SELECT first_name, department_id, salary FROM employees ORDER BY department_id, first_name, salary desc;
Which two statements are true regarding the output of the above query? (Choose two.)
A. The values in all the columns would be sorted in the descending order.
B. The values in the SALARY column would be sorted in descending order for
all the employees having the same value in the DEPARTMENT_ID column.
C. The values in the FIRST_NAME column would be sorted in ascending order
for all the employees having the same value in the DEPARTMENT_ID column.
D. The values in the FIRST_NAME column would be sorted in the descending order
for all the employees having the same value in the DEPARTMENT_ID column.
E. The values in the SALARY column would be sorted in descending order for all
the employees having the same value in the DEPARTMENT_ID and
FIRST_NAME column.
Answer: C E 51
題庫 58
先以 department_id 升冪排序 , 當 department_id 值相同時 , 再以 first_name 升冪排序 , 當 first_name 值相同時 , 再以 salary降冪排序
53
3-28
Substitution Variables (代入變數)使用於:1. WHERE conditions
2. ORDER BY clauses
3. Column expressions
4. Table names
5. Entire SELECT statements
變數值可從以下幾種方式而得 1. file
2. Person
3. 另一個 select statement
54
3-29 單一的 &
單一的 &每一次都會提示使用者輸入數值型態 :
SELECT employee_id, last_name, salary, department_id
FROM employees
WHERE employee_id = &employee_num ;
113
55
3-31 單一的 & date 和 character 值要用單引號括起來
SELECT last_name, department_id, salary*12
FROM employees
WHERE job_id = '&job_title' ;
IT_PROG
56
3-32 單一的 &
SELECT employee_id, last_name, job_id, &column_name
FROM employees
WHERE &condition
ORDER BY &order_column ;
salary
Salary >15000
last_name
57
3-33 && &&
可 reuse 變數只需提示一次 , 不用每次提示輸入且若再執行一次 query時 , 不會再被提示SELECT employee_id, last_name, job_id, &&column_name
FROM employees
ORDER BY &column_name ;
department_id
58
3-35 &&
DEFINE 新增變數並指定變數值
UNDEFINE移除變數
substitution variable存在直到 undefine該變數或離開該 session
DEFINE employee_num = 200 ;
SELECT employee_id, last_name, salary, department_id
FROM employees
WHERE employee_id = &employee_num ;
UNDEFINE employee_num ;
59
3-36 使用 SET VERIFY ON
顯示取代變數前與後的值SET VERIFY ON
SELECT employee_id, last_name, salary
FROM employees
WHERE employee_id = &employee_num;
3-37 Quiz
Which four of the following are valid operators for the WHERE clause?a. >=
b. IS NULL
c. !=
d. IS LIKE
e. IN BETWEEN
f. <>
60
61
4-4 及 4-5 Using Single-Row Functions to Customize Output
SQL function: 不一定有參數 , 但一定會回傳一個值 Two Types of SQL Functions
1. Single-row function : 作用在單一列 , 且每列回傳一個值2. Multiple-Row Functions : 作用在一組列中 , 每一組回傳一個值 ,
又稱為 group functions
62
4-6 Single-Row Functions
Single-Row Functions :修改資料型態nested( 巢狀 )參數可以是欄位或運算式( expression )可用在
1. Select
2. Where
3. Order by
63
4-7 Single-Row Functions Character functions:
輸入 character, 回傳 both character and number 值 Number functions:
輸入 numeric ,回傳 numeric 值 Date functions:
操作在 DATE data typeMONTHS_BETWEEN function,回傳 number其餘回傳 DATE 值
Conversion functions:轉換 data type to another
General functions:NVLNVL2NULLIFCOALESCECASEDECODE
4-11
SELECT 'The job id for ' || UPPER(last_name) || ' is '
|| LOWER(job_id) AS "EMPLOYEE DETAILS"
FROM employees;
65
4-12
SELECT employee_id, last_name, department_id
FROM employees
WHERE LOWER(last_name) = 'higgins';
66
67
4-9 及 4-10 補充 substr ( column|exp, m[,n] ) :取子字串
從第m 位回傳 n 個值回來若m 為負值 , 則從右邊開始m位 , 但取值時 , 一樣是由左到右取 n 位 若 n 值忽略 , 則取從m 位到最後select substr('ABCDEFGH', 1,3) from dual ; ABC select substr('ABCDEFGH', -3,3) from dual; FGHselect substr('ABCDEFGH', 5) from dual ; 少最後參數 , 則取全部
EFGH
instr ( column|exp, ‘string’, [,m], [n] ) :子字串的位置 , 傳回數值從來源字串第m 位開始找出現第 n次的子字串 , 傳回該位置 m 和 n 的預設值為 1select instr('ABCABC', 'A') from dual ; 1select instr('ABCABCABC', 'A',2, 2) from dual ; 7
select instr('ABCABCABC', 'A',2, 3) from dual ; 0 , 找不到第 3個 A
從第 2 個位置開始找
找尋第 2 個 A
68
補充 CONCAT : 結合兩個參數
若要結合三個參數以上 select concat(concat('A','B'),'C') from dual ; ABC或 select 'A'|| 'B'||'C' from dual ;
LENGTH :求字串長度 , 傳回數值 select LENGTH('ABCDEFGH') from dual; 8
LPAD(column|exp ,n,’string’)LPAD( 來源 , 補齊長度 , 補齊的字串 ) 左邊補齊select LPAD('ABC',5,'*') from dual ; **ABC
RPAD(column|exp ,n,’string’)RPAD( 來源 , 補齊長度 , 補齊的字串 ) 右邊補齊select RPAD('ABC',5,'*') from dual ; ABC **
select RPAD('ABC',5,'*?') from dual ; ABC *?
補充 TRIM (leading|trailing|both trim_char FROM trim_source)
去頭尾 , 預設為 both ,亦即預設頭尾皆去掉select TRIM( both 'A' from 'BCABA') from dual ; BCAB
select TRIM( leading 'A' from 'AAAACABA') from dual ; CABA
REPLACE: 取代 REPLACE(text ,search_string, replacement_string)select REPLACE('Black and Blue', 'Bl', 'J') from dual ; Jack and Jue
69
71
4-14 Using the Character-Manipulation Functions
SELECT employee_id, CONCAT(first_name, last_name) NAME,
job_id, LENGTH (last_name) ,
INSTR(last_name, 'a') "Contains 'a'?"
FROM employees
WHERE SUBSTR(job_id, 4) = 'REP' ;
last_nam 最後一個字母為‘ y’ 的員工 select last_name from employees
where SUBSTR(last_name, -1, 1) = 'y';
72
4-16 Numeric Functions
ROUND (column|exp,n): 四捨五入到指定小數位數 ( specified decimal)若 n 省略 , 則到整數位 , 若 n 為負值 , 則從整數位向左數 n 位
TRUNC (column|exp,n): 無條件捨去到指定小數位數若 n省略 , 其預設值為 0
MOD(m,n): 求餘數
73
4-16 Numeric Functions
numeric function :只能接受數字 , 並輸出數字SQL> select ROUND(AA, 2) from dual;
select ROUND(AA, 2) from dual
*
ERROR at line 1:
ORA-00904: "AA": invalid identifier
SQL> select ROUND('AA', 2) from dual;
select ROUND('AA', 2) from dual
*
ERROR at line 1:
ORA-01722: invalid number
74
4-17 Using the ROUND Function DUAL
一個 public table 用以查詢 functions and calculations 結果 (view results)
dual 為 SYS 擁有 , 可以給所有使用者使用 , 包含一個欄位 DUMMY, 一列值為 X
round : 除了數字也可用於 date function SELECT ROUND(45.923,2), ROUND(45.923,0),ROUND(45.923,-
1)
FROM DUAL;
trunc : 也可用於 date function SELECT TRUNC(45.923,2), TRUNC(45.923), TRUNC(45.923,-
1)
FROM DUAL;
75
4-18 Using the TRUNC Function
mod 常用於決定奇 ,偶數mod 是 oracle 的 hash function
SELECT last_name, salary, MOD(salary, 5000) FROM employees WHERE job_id = 'SA_REP';
4-19 Using the MOD Function
76
4-21 Working with Dates dates :
Oracle Database stores dates in an internal numeric format: century, year, month, day, hours, minutes, and seconds
預設日期格式為 DD-MON-RR有效日期 (Valid Oracle dates )
between January 1, 4712 B.C., and December 31, 9999 A.D.
SELECT last_name, hire_date
FROM employees
WHERE hire_date < '01-FEB-88' ;
select sysdate from dual;
SELECT last_name,hire_dateFROM employeesWHERE hire_date = '07-6月 -02';
不是有效的月份
77
4-21 Working with Dates
alter session set nls_date_format ='YYYY-MM-DD:HH24:MI:SS';
alter session set nls_date_format ='DD-MON-RR';
alter session set nls_date_language =french
alter session set nls_date_language =american
SQL> select sysdate from dual;
SYSDATE
--------------
31-8 月 -13
79
4-24 Using the SYSDATE Function sysdate
顯示資料庫所在地點的時間select sysdate from dual;
current_date 顯示該 session time zone 的時間select current_date from dual;
4-25
database 將 date 儲存成數字
80
4-26 Using Arithmetic Operators with Dates
SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS
FROM employees
WHERE department_id = 90;
81
4-28 Date-Manipulation Functions months_between(date1,date2)
兩個日期間的月份數 ,回傳值可為正或負若 date1 > date 2 , 則回傳正值
add_months(date,n) 日期加上 n n 需為整數字且可為負值
last_day 當月最後一天 next_day (date,'char')
下一個指定日 (星期幾 ) 的日期 如下週一的日期 next_day(sysdate,'星期一 ') char 可為字串或數字 , 若 char 為數字 , 在 America 1 代表 Sunday
82
4-29 Using Date Functions
select MONTHS_BETWEEN('01-9月 -95','11-1月 -94') from dual;19.6774194
select MONTHS_BETWEEN('11-1月 -94','01-9月 -95') from dual; -19.6774194
select ADD_MONTHS ('31-1月 -96',1) from dual; '29-2月 -96'
select ADD_MONTHS ('31-1月 -96',-1) from dual; '31-12月 -95'
select NEXT_DAY ('01-9月 -95','星期五 ') from dual; '08-9月 -95'
select LAST_DAY ('01-2月 -95') from dual; '28-2月 -95'
補充 :118. a monthly bonus of $50 to all the employees who have completed five years in the company.SELECT last_name, department_id, salary+50*12 "Annual Compensation" FROM employees WHERE MONTHS_BETWEEN(SYSDATE, hire_date)/12 >= 5; When you execute the statement, the "Annual Compensation" is not computed correctly. What changes would you make to the query to calculate the annual compensation correctly?
A. Change the SELECT clause to SELECT last_name, department_id,
salary*12+50 "Annual Compensation".
B. Change the SELECT clause to SELECT last_name, department_id,
salary+(50*12) "Annual Compensation".
C. Change the SELECT clause to SELECT last_name, department_id,
(salary+50)*12 "Annual Compensation".
D. Change the SELECT clause to SELECT last_name, department_id,
(salary*12)+50 "Annual Compensation".
Answer: C 83
題庫 118
對於來公司滿 5 年的員工 , 要給他每個月 50元的獎金 ; 查詢的欄位有 last_name, department_id 和 Annual Compensation ( 年薪 )
執行時 Annual Compensation ( 年薪 ) 計算不正確 , 如何修正 ?
84
4-29 Using Date Functions
SELECT employee_id, hire_date, MONTHS_BETWEEN (SYSDATE, hire_date)
TENURE, ADD_MONTHS (hire_date, 6) REVIEW, NEXT_DAY (hire_date,'FRIDAY') , LAST_DAY(hire_date)
FROM employees
WHERE MONTHS_BETWEEN (SYSDATE, hire_date) < 150 ;
補充 :30.SELECT first_name, employee_id, NEXT_DAY(ADD_MONTHS (hire_date, 6), 1) "Review" FROM employees; The review date is the first Monday after the completion of six months of the hiring. The NLS_TERRITORY parameter is set to AMERICA in the session. Which statement is true regarding this query?
A. The query would execute to give the desired output.
B. The query would not execute because date functions cannot be nested.
C. The query would execute but the output would give review dates that
are Sundays.
D. The query would not execute because the NEXT_DAY function accepts
a string as argument.
Answer: C
85
題庫 30
查詢員工受雇滿 6 個月後的第一個星期一 ,使用美國日期格式 , 注意 : 美國每星期的第一天是星期日
86
4-30 Using ROUND and TRUNC Functions with Dates
round(date,'fmt') 以 fmt 格式來做四捨五入若 fmt 為month, 則 day(日 ) >=16 進位到下個月的 1日 , <=15
為當月的 1 日若 fmt 為 year, 則 month( 月份 )為 1~6 月為當年 1月 1日 ,
7~12 月為下一年的 1月 1 日 若 fmt 省略 , 則為 day
87
4-30 Using ROUND and TRUNC Functions with Dates
SELECT employee_id, hire_date,
ROUND(hire_date, 'MONTH') , TRUNC(hire_date, 'MONTH')
FROM employees
WHERE hire_date LIKE '%03' ;
88
4-31 Quiz
Which four of the following statements are true about single-row functions?a. Manipulate data items
b. Accept arguments and return one value per argument
c. Act on each row that is returned
d. Return one result per set of rows
e. May not modify the data type
f. Can be nested
g. Accept arguments that can be a column or an expression
補充 :86.Which three statements are true regarding single-row functions? (Choose three.)
A. They can accept only one argument.
B. They can be nested up to only two levels.
C. They can return multiple values of more than one data type.
D. They can be used in SELECT, WHERE, and ORDER BY clauses.
E. They return data type can be different from the data type of the
argument that is referenced.
F. They can accept a column name, expression, variable name, or a
user-supplied constant as arguments.
Answer: D E F 89
題庫 86
可接受不只一個參數 , 如 : months_between(date1,date2)
可以巢狀不只二層
回傳的值只能一個且只能為一種資料型態
參數資料型態不一樣 , 回傳的資料型態也會不一樣 ,如 :round(date,‘fmt’) 回傳日期的資料型態round(45.923,2) 回傳數字的資料型態