month()
函数返回整数,这就是没有前导零的原因。您可以使用lpad(month,2,0)
格式化月份的函数:
hive> select lpad(month('2017-09-01'),2,0);
OK
09
Time taken: 0.124 seconds, Fetched: 1 row(s)
hive> select lpad(month('2017-10-01'),2,0);
OK
10
Time taken: 0.433 seconds, Fetched: 1 row(s)
或者你可以使用substr()
从日期中提取年份和月份:
hive> select substr('2017-10-01',1,4) as year, substr('2017-10-01',6,2) as month;
OK
year month
2017 10
Hive 2.1.0 (HIVE-13248) 之前的 date_sub() 函数返回类型是 String,因为创建该方法时不存在 Date 类型。看这里:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF