Hive QL内置日期和时间处理函数
Hive提供有许多内置函数来帮助我们处理和查询数据,包括:
- 字符串操作函数
- 数据操作函数
- 类型转换函数
- 条件运算符函数
- 数学函数
官方文档参考:查看
一、Hive日期和时间处理函数
to_date():返回时间字符串的日期部分。
-- 语法:to_date(string timestamp)
-- 提取“2019-11-06 16:20:45”的日期部分
select to_date('2019-11-06 16:20:45');
year()、month()、day():从一个日期中取出相应的年、月、日。
-- 语法:year(string date)
-- month(string date)
-- day(string date)
-- 从“2019-11-06 16:20:45”中提取年、月、日
select year('2019-11-06 16:20:45'),month('2019-11-06 16:20:45'),day('2019-11-06 16:20:45');
weekofyear():返回输入日期在该年中是第几个星期。
-- 语法:weekofyear(string date)
select weekofyear('2019-11-06 16:20:45');
datediff():计算开始时间startdate到结束时间enddate相差的天数。
-- 语法:datediff(string enddate, string startdate)
-- 计算'2019-11-06 16:32:23'和'2018-11-06 16:32:23'之间相差多少天
select datediff('2019-11-06 16:32:23','2018-11-06 16:32:23');
current_date():返回当前日期。
select current_date(); -- 张三2005年6月4日入职,请问他现在的工龄是多少年? select floor(datediff(current_date(),'2005-06-04')/365);
date_add():在一个日期基础上增加天数。
date_sub():在一个日期基础上减去天数。
-- 语法:date_add(string startdate, int days)
-- date_sub(string startdate, int days)
-- 请问,三天以后的日期是?三天前的日期是?
select date_add('2019-11-06',3) as `三天后`, date_sub('2019-11-06',3) as `三天前`;
select date_add('2019-11-06',3) `三天后`, date_sub('2019-11-06',3) `三天前`;
select date_add(current_date(),3) as `三天后`, date_sub(current_date(),3) as `三天前`;
date_format():按指定格式返回时间(对日期时间格式化)。
-- 语法:date_format(date/timestamp/string ts, string fmt)
-- 将“2019-11-06 17:32:23”转化为月日(01-11)的格式
select date_format('2019-11-06 17:32:23', 'MM-dd');
select date_format('2019-11-06 17:32:23', 'MM-dd-yyyy');
select date_format('2019-11-06 17:32:23', 'MM/dd/yyyy');
select date_format('2019-11-06 17:32:23', 'MM/dd/yyyy HH:mm:ss');
select date_format('2019-11-06 17:32:23', 'yyyy年MM月dd日 HH点mm分ss秒');
二、条件函数
if():if函数。
-- 语法:if(boolean testCondition, T valueTrue, T valueFalseOrNull) -- 如果testCondition 为true就返回valueTrue,否则返回valueFalseOrNull 。 select if(25.80 > 10,'贵','便宜'); select if(25.80 < 10,'贵','便宜');
COALESCE():非空查找。
-- 语法:COALESCE(T v1, T v2, …)
-- 返回参数中的第一个非空值;如果所有值都为NULL,那么返回NULL
select coalesce(null, '地址不详','地址不清楚');
select coalesce('地址不清楚',null, '地址不详');
isnull(),isnotnull():判断是否为NULL。
-- 语法:isnull(a) 如果a为null就返回true,否则返回false
-- isnotnull(a) 如果a为非null就返回true,否则返回false
select isnull(23);
select isnull(null);
select isnull('');
select isnotnull('');
CASE...WHEN...:条件判断。
/* 语法:
CASE a
WHEN b THEN c
[WHEN d THEN e]*
[ELSE f]
END
如果a=b就返回c,a=d就返回e,否则返回f
*/
select case 150
when 300 then 'aaa'
when 200 then 'sss'
when 100 then 'ddd'
else 'fff'
end as `result`;
case when语句:常用在机器学习数据打标签上。
create table if not exists price_label as
select jcmc,
case
when bqjg>25 then 2
when bqjg<10 then 0
else 1
end as label
from pricewatch;
select * from price_label limit 10;