简体   繁体   中英

How can I get Quarter to Date in Hive SQL?

I'm having a hard time getting the quarter to date values from Hive SQL. How can I get the first day of the current quarter in Hive sql?

Table name: Orders

Fields: date, order_num, sales_num

Please advise.

This seems to be the cleanest way

with t as (select date '2016-08-27' as dt) 
select add_months(trunc(dt,'MM'),-(month(dt)-1)%3) from t
;

2016-07-01


Here are 2 more options

with t as (select date '2016-08-27' as dt) 
select  trunc(add_months(dt,-(month(dt)-1)%3),'MM') 
from    t
;

2016-07-01


with t as (select date '2016-08-27' as dt) 
select  add_months(trunc(dt,'YY'),cast((month(dt)-1) div 3 * 3 as INT)) 
from    t
;

2016-07-01

For earlier versions

with t as (select '2016-08-27' as dt)
select  printf('%04d-%02d-%02d',year(dt),(((month(dt)-1) div 3) * 3) + 1,1)
from    t

2016-07-01

Same, but for today

with t as (select from_unixtime(unix_timestamp(),'yyyy-MM-dd') as today)
select  printf('%04d-%02d-%02d',year(today),(((month(today)-1) div 3) * 3) + 1,1) as 
from    t

2017-04-01

If you can't use the various date function that Dudu suggested, you can always cast it to string, parse out the month, and use a case statement. Depending on your version of Hive, you may have to use a simple case instead of searched.

(assuming YYYY-MM-DD)

case cast (substring (cast(<date field> as varchar(10)),6,2) as integer)
when between 1 and 3 then 1
when between 4 and 6 then 2
when between 7 and 9 then 3
else 4
end

Ugly, but it should work.

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