如何在 Hive SQL 中为日期列执行 BETWEEN 运算符
How to perform a BETWEEN operator in Hive SQL for date column
我会尽可能清楚地解释我的问题。我想按日期过滤 table(只选择日期包含在 当前月份 中的记录),在 Oracle SQL 中我使用以下内容查询实现这样的目标:
select * from table t1
where t1.DATE_COLUMN between TRUNC(SYSDATE, 'mm') and SYSDATE
如何在 Hive SQL 中复制相同的过滤器?我应该用来应用过滤器的列是 TIMESTAMP 类型的列(例如 2017-05-15 00:00:00)。
我正在使用 CDH 5.7.6-1。
有什么建议吗?
您可以格式化为字符串:
where date_format(t1.DATE_COLUMN, 'y-m') = date_format(current_timestamp, 'y-m')
我意识到我现在无法访问 Hive。文档建议 'y-m'
,但 Java 文档建议 'yyyy-mm'
.
请注意 unix_timestamp
不是固定的,会在查询期间发生变化。
因此,它不能用于分区消除。
对于较新的 Hive 版本,请改用 current_date
/ current_timestamp
。
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF
select *
from table t1
where t1.DATE_COLUMN
between cast(from_unixtime(unix_timestamp(),'yyyy-MM-01 00:00:00') as timestamp)
and cast(from_unixtime(unix_timestamp()) as timestamp)
;
select cast (from_unixtime(unix_timestamp(),'yyyy-MM-01 00:00:00') as timestamp)
,cast (from_unixtime(unix_timestamp()) as timestamp)
;
+---------------------+---------------------+
| _c0 | _c1 |
+---------------------+---------------------+
| 2017-05-01 00:00:00 | 2017-05-16 01:04:55 |
+---------------------+---------------------+
我会尽可能清楚地解释我的问题。我想按日期过滤 table(只选择日期包含在 当前月份 中的记录),在 Oracle SQL 中我使用以下内容查询实现这样的目标:
select * from table t1
where t1.DATE_COLUMN between TRUNC(SYSDATE, 'mm') and SYSDATE
如何在 Hive SQL 中复制相同的过滤器?我应该用来应用过滤器的列是 TIMESTAMP 类型的列(例如 2017-05-15 00:00:00)。
我正在使用 CDH 5.7.6-1。
有什么建议吗?
您可以格式化为字符串:
where date_format(t1.DATE_COLUMN, 'y-m') = date_format(current_timestamp, 'y-m')
我意识到我现在无法访问 Hive。文档建议 'y-m'
,但 Java 文档建议 'yyyy-mm'
.
请注意 unix_timestamp
不是固定的,会在查询期间发生变化。
因此,它不能用于分区消除。
对于较新的 Hive 版本,请改用 current_date
/ current_timestamp
。
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF
select *
from table t1
where t1.DATE_COLUMN
between cast(from_unixtime(unix_timestamp(),'yyyy-MM-01 00:00:00') as timestamp)
and cast(from_unixtime(unix_timestamp()) as timestamp)
;
select cast (from_unixtime(unix_timestamp(),'yyyy-MM-01 00:00:00') as timestamp)
,cast (from_unixtime(unix_timestamp()) as timestamp)
;
+---------------------+---------------------+
| _c0 | _c1 |
+---------------------+---------------------+
| 2017-05-01 00:00:00 | 2017-05-16 01:04:55 |
+---------------------+---------------------+