【问题标题】:AWS Athena: How to escape reserved word column name and cast to integerAWS Athena:如何转义保留字列名并转换为整数
【发布时间】:2022-08-13 23:20:54
【问题描述】:

我有一个名为 \'timestamp\' 的列,它是一个保留字。我需要选择该列,然后将其转换为整数以执行下面的查询。我可以成功地对列数据进行简单的选择。只有当我尝试将值转换为整数时,才会返回错误。

我试图按照AWS Docs 中的建议使用反引号和双引号来转义保留字,但没有成功。

用反引号查询:

SELECT `timestamp`
FROM my_table
WHERE from_unixtime(cast(`timestamp` as integer)) >= date_add(\'day\', -7, now())

错误:

Queries of this type are not supported

用双引号查询:

SELECT \"timestamp\"
FROM my_table
WHERE from_unixtime(cast(\"timestamp\" as integer)) >= date_add(\'day\', -7, now())

错误:

INVALID_CAST_ARGUMENT: Cannot cast \'\' to INT

谢谢!

    标签: sql casting amazon-athena


    【解决方案1】:

    问题不在于您的转义逻辑,而在于您的数据集在时间戳列中包含无法转换的空字符串。您可以通过过滤掉空字符串记录来避免这种情况。

    SELECT "timestamp"
    FROM (SELECT "timestamp" from my_table where "timestamp" != '')
    WHERE from_unixtime(cast("timestamp" as integer)) >= date_add('day', -7, now())
    

    【讨论】:

    • 既然你指出了这一点,错误就很明显了。谢谢!
    【解决方案2】:

    您可以使用try_cast 而不是cast,它在强制转换失败的情况下返回null(空字符串不能转换为integer),这将导致where 条件评估为false:

    with dataset(col) as (
        values (''),
        ('1659648600')
    )
    
    select *
    from dataset
    where from_unixtime(try_cast(col as integer)) >= date '2022-08-03';
    

    输出:

    col
    1659648600

    【讨论】:

    • 谢谢,我不知道 try_cast()。
    • @CaptainCaveman 还有一个try 可以在类似情况下使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2021-12-07
    相关资源
    最近更新 更多