6. Examine the structure of the SHIPMENTS table:

name           Null       Type

PO_ID          NOT NULL    NUMBER(3)

PO_DATE        NOT NULL    DATE

SHIPMENT_DATE NOT NULL    DATE

SHIPMENT_MODE             VARCHAR2(30)

SHIPMENT_COST             NUMBER(8,2)

You want to generate a report that displays the PO_ID and the penalty amount to be paid if the

SHIPMENT_DATE is later than one month from the PO_DATE. The penalty is $20 per day.

Evaluate the following two queries:

SQL> SELECT po_id, CASE

WHEN MONTHS_BETWEEN (shipment_date,po_date)>1 THEN

TO_CHAR((shipment_date - po_date) * 20) ELSE 'No Penalty' END PENALTY

FROM shipments;

SQL>SELECT po_id, DECODE

(MONTHS_BETWEEN (po_date,shipment_date)>1,

TO_CHAR((shipment_date - po_date) * 20), 'No Penalty') PENALTY   

FROM shipments;

Which statement is true regarding the above commands?

A. Both execute successfully and give correct results.

B. Only the first query executes successfully but gives a wrong result.

C. Only the first query executes successfully and gives the  correct result.

D. Only the second query executes successfully but gives a wrong result.

E. Only the second query executes successfully and gives the correct result.

Answer: C

答案解析:

参考:javascript:void(0)

javascript:void(0)


题意要求: 显示PO_ID和支付的罚款总金额,SHIPMENT_DATE与PO_DATE进行比较,SHIPMENT_DATE如果比PO_DATE晚一个月,则每天罚款$20。


MONTHS_BETWEEN(date1, date2): 返回date1和date2两个日期之间间隔几个月,结果可以为正或为负。如果date1晚于date2则结果为正;如果date1早于date2则结果为负;结果的非整数部分也代表月间隔的一部分。
 
DECODE(expr,search1,result1[,search2,result2……,default]):比较expr与search,如果等于search1则返回result1,如果等于search2则返回result2,依次类推,如果都不等于,如果有default则返回default,否则返回NULL.
ORACLE在比较之前,会自动把expr和每一个search隐式转换成第一个search(search1)的数据类型。自动把返回值转换成第一个result(result1)的数据类型。如果第一个result的数据类型为CHAR或者值是null,则Oracle转换返回值为VARCHAR2. 
在DECODE函数中,NULL是相等的,如果expr为空,则Oracle将会返回第一个为NULL的search所对应的result。DECODE列表中的最大表达式个数为255个。

第一个SQL的表达是正确,可以正确执行的。其实我觉得这道题的答案有点出入,MONTHS_BETWEEN返回的是月数,每天罚款$20,相乘起来,因为一个是天的单位,一个是月的单位,如果题中改成每月罚款20,则才是正确的。
 DECODE 的表达是错误的。
sh@TEST0924> SELECT po_id, DECODE (MONTHS_BETWEEN (po_date,shipment_date)>1,
  2  TO_CHAR((shipment_date - po_date) * 20), 'No Penalty') PENALTY
  3  FROM shipments;
SELECT po_id, DECODE (MONTHS_BETWEEN (po_date,shipment_date)>1,
                                                            *
ERROR at line 1:
ORA-00907: missing right parenthesis