Athena 中的 cast 和 left 函数
cast and left functions in Athena
转换和转换功能在 Athena 中按预期工作:
SELECT code_2 as mydate, cast( code_2 as varchar) from some_table
但是如何提取最左边的 8 个字符?这会引发错误:
SELECT code_2 as mydate, left(cast( code_2 as varchar),8) as date from some_table
这里是错误:
extraneous input 'left' expecting
尝试直接投射到 VARCHAR(8)
:
SELECT
code_2 AS mydate,
CAST(code_2 AS VARCHAR(8))
FROM some_table;
我从未使用过 Athena,但文档暗示这应该有效。此技巧适用于 Oracle、SQL Server、Postgres 和 MySQL.
如果code_2
是字符串,则使用substr()
:
select code_2 as mydate, substr(code_2, 1, 8) as date
from some_table;
如果code_2
是一个日期,那么使用合适的日期函数:
select code_2 as mydate,
date_format(code_2, '%Y-%m-%d') as date
from some_table;
使用适合数据类型的函数。当有内置函数可以完全满足您的需求并为您提供更多控制权时,请不要将日期转换为字符串。
转换和转换功能在 Athena 中按预期工作:
SELECT code_2 as mydate, cast( code_2 as varchar) from some_table
但是如何提取最左边的 8 个字符?这会引发错误:
SELECT code_2 as mydate, left(cast( code_2 as varchar),8) as date from some_table
这里是错误:
extraneous input 'left' expecting
尝试直接投射到 VARCHAR(8)
:
SELECT
code_2 AS mydate,
CAST(code_2 AS VARCHAR(8))
FROM some_table;
我从未使用过 Athena,但文档暗示这应该有效。此技巧适用于 Oracle、SQL Server、Postgres 和 MySQL.
如果code_2
是字符串,则使用substr()
:
select code_2 as mydate, substr(code_2, 1, 8) as date
from some_table;
如果code_2
是一个日期,那么使用合适的日期函数:
select code_2 as mydate,
date_format(code_2, '%Y-%m-%d') as date
from some_table;
使用适合数据类型的函数。当有内置函数可以完全满足您的需求并为您提供更多控制权时,请不要将日期转换为字符串。