简体   繁体   中英

How to extract day/month/year etc from varchar date field, using Presto?

I currently have tables with dates, set up as VARCHAR in the format of YYYY-MM-DD such as:

2017-01-01

The date column I'm working with is called 'event_dt'

I'm used to being able to use day(event_dt), month(event_dt), year(event_dt) etc. in Hive, but Presto just gives me error executing query with no other explanation when the queries fail.

So, for example, I've tried:

select
month(event_dt)
from
my_sql_table
where
event_dt = '2017-01-01'

I would expect the output to read:

01

but all I get is [Code: 0, SQL State: ] Error executing query

I've tried a few other methods listed in the Presto documentation but am having no luck at all. I realize this is probably very simple but any help would be much appreciated.

You can use themonth() function after converting the varchar to a date with the date() function:

presto> select month(date('2017-01-01'));
 _col0
-------
     1
(1 row)

Thanks to @LukStorms in the comments to the original question, I've found two solutions:

  1. Using month(cast(event_dt as date))
  2. Using month(date(event_dt))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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