sql - 在 Hive 中将时间戳 (HH:mm:ss) 转换为秒的任何更好的方法
问题描述
我有一个字符串类型的配置单元字段,其时间戳采用以下格式:HH:mm:ss mm:ss ss 我需要将它们转换如下:
Input:
10:30:40
30:40
40
Output Expected:
10:30:40 = (10*3600) + (30 * 60) + 40 = 37,840
30:40 = (30 * 60) + 40 = 1840
40 = 40 = 40
我试着做这样的事情
case
when duration like '%:%:%' then
split(duration, ':')[0] * 3600 +
split(duration, ':')[1] * 60 +
split(duration, ':')[2]
when duration like '%:%' then
split(duration, ':')[0] * 60 +
split(duration, ':')[1]
else
duration
end
这可行,但似乎效率低下。当我必须处理数十亿条记录时,有没有更好的方法来做同样的事情。
解决方案
在 hive 中执行时,您的表达式不会产生太多额外的负载。您可以使用函数稍微简化查询unix_timestamp
,但它不会运行得更快。
with input as(--use your table instead of this
select stack(3, '10:30:40',
'30:40',
'40') as duration
)
select duration, case when duration like '%:%:%' then unix_timestamp(duration,'HH:mm:ss')
when duration like '%:%' then unix_timestamp(duration,'mm:ss')
else duration
end as result
from input
结果:
duration result
10:30:40 37840
30:40 1840
40 40
或者更简单:
select duration, coalesce(unix_timestamp(duration,'HH:mm:ss'), unix_timestamp(duration,'mm:ss'), duration) as result
返回完全相同。
推荐阅读
- angular - Angular ngx-mqtt - 使用用户在表单上输入的值而不是 app.module.ts 中的硬编码值连接到 mqtt 代理
- javascript - 带有 Express 和 http 代理中间件的 Docker - 如何使路由仅接受内部路由
- java - 不要在片段中显示列表视图项
- python - 如何使用 image_dataset_from_directory 为 AutoKeras ImageRegressor 构建 tf.Data.Dataset?
- r - 如何用颜色打印 R 数据框?
- java - 生成带有出现子串的矩阵
- vba - 发送邮件时抄送收件人与收件人合并
- r - 获取可用的数据
- python - 我需要在 GTK 中同时处理多个窗口,但是当我隐藏并显示那个时间时,核心转储错误显示和应用程序?关闭
- amazon-cloudwatch - 使用目标 sns 在 cloudwatch 中捕获事件