首页 > 解决方案 > Case expression for date format conversion

问题描述

I have an Entrydate column that comes from Source in below date formats

  1. YYYY-MM-DD HH.MM.SS
  2. YYYY-MM-DD

It is loaded to a table as YYYYMM format. I am looking for a case expression that handles both the conditions.

I am using the below SQL

SELECT 
    CASE 
       WHEN to_char(ENTRYDATE, 'YYYY-MM-DD HH.MM.SS') 
          THEN to_char(ENTRYDATE, 'YYYYMM')
       to_char(ENTRYDATE, 'YYYY-MM-DD') 
          THEN to_char(ENTRYDATE, 'YYYYMM')
FROM 
    TABLE;

but I get this error:

ORA-00920: invalid relational operator

I will need to get the date in YYYYMM format to validate the output table.

标签: sqloracle

解决方案


您得到的原因invalid relational operator是该函数TO_CHAR()不返回布尔值。

我的猜测是,您将表面上的日期值存储为CHARor VARCHAR,并且您需要转换为某种格式。如果它们被存储为DATE值,那么你应该没什么可做的。但假设CHAR// VARCHARVARCHAR2

SELECT CASE WHEN REGEXP_LIKE(entrydate, '^\d{4}-\d{2}-\d{2}( \d{2}\.\d{2}\.\d{2})$')
         THEN REGEXP_REPLACE(entrydate, '^(\d{4})-(\d{2}).*$', '\1\2')
       END AS yyyymm_date
  FROM table;

(请注意,您的陈述中也缺少一个ENDCASE

NULL如果 的值entrydate是其他格式,则上面将返回 a 。

希望这可以帮助。


推荐阅读