Search code examples
sqlapachedatetimeapache-drill

Get week of the year from date in apache drill


I'm trying to convert a timestamp in some data (using apache drill) to the week of year.

According to the reference the closet thing I can see is the "extract" function however this only works for YEAR, MONTH, DAY, HOUR, MINUTE, SECOND units.

Original date example

ID, START_DATE
1, 2014-07-07T13:20:34.000Z 

Query (something like this)

SELECT ID, EXTRACT(WEEK, START_DATE) FROM MY_TABLE; 

And get a result like this:

ID, START_DATE
1, 27 

Solution

  • I came across this problem a few weeks later again and rather than writing a function in drill (as I felt this was to much and I needed just a rough estimate of a week) I did the following instead:

    # 7 * 24 * 60 * 60 = 604800
    
    select
      START_DATE as `ORIGINAL DATE`,
      TRUNC(CAST((CAST((UNIX_TIMESTAMP(START_DATE,'yyyy-MM-dd HH:mm:ss.SSS') - UNIX_TIMESTAMP(EXTRACT(year FROM TO_DATE(START_DATE, 'yyyy-MM-dd HH:mm:ss.SSS')),'yyyy')) AS FLOAT) / CAST(604800 AS FLOAT)) AS FLOAT)) + 1 as `WEEK_NO`,
      EXTRACT(year FROM TO_DATE(START_DATE, 'yyyy-MM-dd HH:mm:ss.SSS')) as `YEAR`
    from
      GAME_DATA
    order by
      START_DATE
    limit 10;