使用Case和To_Char

时间:2016-08-25 15:39:29

标签: sql oracle

有人可以帮我解决下面的问题吗?

select  CASE ( TO_CHAR (creation_date ,'MON')
 WHEN 'JAN' THEN 1
 WHEN 'FEB' THEN 2
 WHEN 'MAR' THEN 3
 WHEN 'APR' THEN 4 
 ELSE 'NULL') AS PERIOD 
from po_line_locations_all

我收到错误消息 -

  

ORA-00907:缺少右括号   00907. 00000 - "错过右括号"。

我不是专家所以如果有人可以帮我解决上述问题。

非常感谢 丹

2 个答案:

答案 0 :(得分:2)

您需要select CASE TO_CHAR (creation_date ,'MON') WHEN 'JAN' THEN 1 WHEN 'FEB' THEN 2 WHEN 'MAR' THEN 3 WHEN 'APR' THEN 4 ELSE NULL END AS PERIOD from po_line_locations_all; ,而且不需要括号:

NULL

也不应引用ELSE。实际上NULL是多余的,因为select CASE TO_CHAR (creation_date ,'MON') WHEN 'JAN' THEN 1 WHEN 'FEB' THEN 2 WHEN 'MAR' THEN 3 WHEN 'APR' THEN 4 END AS PERIOD from po_line_locations_all; 是默认值:

public $postLink(){
    this.log.debug('postLink all done');
}

答案 1 :(得分:2)

托尼·安德鲁斯说得对,但我不会去to_char 'MON',因为这取决于你的语言。我去了extract

 select
     Case 
       when extract(MONTH from creation_date ) > 4 then NULL
       else extract(MONTH from creation_date )  end AS PERIOD
  from po_line_locations_all;

这就是为什么这是一个坏主意:

 alter session set NLS_LANGUAGE = 'ENGLISH';
 select extract(MONTH from sysdate) extr, to_char(sysdate,'MON') tochar from dual;
 alter session set NLS_LANGUAGE = 'SPANISH';
 select extract(MONTH from sysdate) extr, to_char(sysdate,'MON') tochar from dual;

<强>输出

Session altered.
      EXTR TOCHAR
---------- ------
         8 AUG

Session altered.
      EXTR TOCHAR
---------- ------
         8 AGO