在redshift中将文本转换为日期

时间:2014-02-01 16:25:56

标签: amazon-redshift

我已将日期保存为文字类型。有一些无效日期阻止我运行任何与日期相关的操作。对于例如

select case when deliver_date = '0000-00-00 00:00:00' then '2014-01-01' else deliver_date::date end as new_date, count(*) as cnt  from some_table group by new_date
Error in query: ERROR: Error converting text to date

我正在使用以下似乎有效的解决方法。

select left(deliver_date,10) as new_date, count(*) as cnt  from sms_dlr group by new_date

但我想知道是否可以将此列转换为日期。

2 个答案:

答案 0 :(得分:2)

尝试删除::date部分:

select
    cast(
        case
            when deliver_date = '0000-00-00 00:00:00' then '2014-01-01'
            else deliver_date
        end
        as date
    ) as new_date,
    count(*) as cnt
from some_table
group by new_date

答案 1 :(得分:1)

您需要分隔有效和无效的日期值。

一种解决方案是使用正则表达式 - 我会让你决定你想要的程度,但这将广泛涵盖日期和日期时间值:

SELECT 
    CASE 
    WHEN 
        deliver_date SIMILAR TO '[0-9]{4}-[0-9]{2}-[0-9]{2}' 
        OR deliver_date SIMILAR TO '[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}'  
    THEN TO_DATE(deliver_date, 'YYYY-MM-DD')
    ELSE TO_DATE('2014-01-01', 'YYYY-MM-DD') 
    END as new_date,
    COUNT(*) as cnt
FROM some_table
GROUP BY new_date