HiveQL或trino(presto):查询

工作中在用大数据,hive、impala、trino都有使用,使用hive和trino最多,整里了以下内容,有点长,看完,绝对有收获。

提示: 上面的代码是hive,下面的代码是trino,文字说明用的是hive。

select name,salary from hive.presto.employees;
select e.name,e.salary from hive.presto.employees e;

当用户选择的列是集合类型,hive会使用JSON语法应用于输出。注意,集合的字符串元素是加上引号的,而基本数据类型string的列值是不加引号的。

  name    salary    subordinates
John Doe  100,000   ['Mary Smith','Todd Jonhes']

deductions列是一个Map,其实用JSON格式来表达map,即使用一个被括在{…}内的以逗号分隔的键:值对列进行表示:

select e.name, e.deductions from hive.presto.employees e;
--trino:
name            address
John Doe    {street=1 Michigan Ave., city=Chicago, state=IL, zip=60600}

数组索引是基于0的,这个和Java中是一样的。这里是一个选择subordinates数组中的第一个元素的查询:

select name,subordinates[0] from hive.presto.employees;
select date(substr('1970-01-01 00:00:00',1,10));
select date(format_datetime(cast('1970-01-01 00:00:00' as timestamp),'yyyy-MM-dd'));
2、year:返回时间字符串中的年份并使用int类型表示
select year('1970-01-01 00:00:00');
select month(cast('1970-11-01 00:00:00' as timestamp));
4、day:返回时间字符串中的天并使用int类型表示
select day("1970-11-12 00:00:00");
select hour(cast('2009-07-30 12:58:59' as timestamp));
select hour(cast('12:58:59' as time));
6、minute:返回分钟数
7、second:返回时间字符串中的秒数
8、datediff:计算两个时间相差的天数
select datediff('2022-01-01','2022-05-25');
select date_diff('month',date'2022-01-01',date'2022-05-25');
select date_diff('year',date'2022-01-01',date'2025-05-25');
9、date_add:增加天数
select date_add('2022-05-23',1);
select date_add('day',-1,current_date);

hive中用trunc,trino中用date_trunc

工作中遇到了一个问题就是,求两时间相差的秒数,以前环境用的DB2 能使用自定义函数实现,换成大数据就没了。

解决方案:

hive中:用 unix_timestamp 转成unix时间戳,然后计算两个日期相差秒数

select
 unix_timestamp(concat(substr('20170728102031',1,4),'-',substr('20170728102031',5,2),'-',substr('20170728102031',7,2),' ',substr('20170728102031',9,2),':',substr('20170728102031',11,2),':',substr('20170728102031',13,2)))
-
unix_timestamp(concat(substr('20170728112031',1,4),'-',substr('20170728112031',5,2),'-',substr('20170728112031',7,2),' ',substr('20170728112031',9,2),':',substr('20170728112031',11,2),':',substr('20170728112031',13,2)))

trino中的实现:使用to_unixtime将时间戳转换成 UNIX 时间,再相减,转换成毫秒后就可以想变成啥变成啥。时分秒任你选。

select to_unixtime(cast('2019-09-09 12:32:05' as timestamp))
-to_unixtime(cast('2019-09-08 12:32:05' as timestamp))

有问题或纰漏错误等,欢迎大家指正。

关于trino时间函数的其他操作,请看下面的文章:

Original: https://blog.csdn.net/weixin_42771366/article/details/124769128
Author: 三生暮雨渡瀟瀟
Title: HiveQL或trino(presto):查询

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/818053/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球