简体   繁体   English

AWS Athena:如何转义保留字列名并转换为 integer

[英]AWS Athena: How to escape reserved word column name and cast to integer

I have a column named 'timestamp' which is a reserved word.我有一个名为“时间戳”的列,它是一个保留字。 I need to select the column then cast it as an integer to perform the query below.我需要 select 列然后将其转换为 integer 以执行下面的查询。 I can successfully perform a simple select of the column data.我可以成功执行一个简单的 select 的列数据。 It is only when I try to cast the value as an integer that the error is returned.只有当我尝试将值转换为 integer 时才会返回错误。

I have tried to escape the word using backticks and double quotes as suggested in the AWS Docs without success.我试图按照AWS Docs中的建议使用反引号和双引号来转义这个词,但没有成功。

*The query works with another table that does not use a reserved word for the column name. *该查询适用于另一个不使用保留字作为列名的表。 This is what I have attempted:这是我尝试过的:

Query with reserved word un-escaped:保留字未转义的查询:

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

Error:错误:

INVALID_CAST_ARGUMENT: Cannot cast '' to INT

Query with backticks:用反引号查询:

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

Error:错误:

Queries of this type are not supported

Query with double quotes:用双引号查询:

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

Error:错误:

INVALID_CAST_ARGUMENT: Cannot cast '' to INT

Thanks!谢谢!

The problem is not your escaping logic, but that your dataset contains empty strings in the timestamp column which can not be casted.问题不在于您的 escaping 逻辑,而是您的数据集在时间戳列中包含无法转换的空字符串。 You can avoid that, by filtering out the empty string records.您可以通过过滤掉空字符串记录来避免这种情况。

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

Instead of cast you can use try_cast which returns null in case of unsuccessful cast (empty string can't be turned into integer ), which will result in the where condition evaluated to false:您可以使用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';

Output: Output:

col山口
1659648600 1659648600

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM