HiveQL,Hive SQL选择日期范围

时间:2014-10-10 17:37:43

标签: datetime hiveql

在SQL中似乎很简单,但我在使用日期范围的HiveQL时遇到了麻烦。

我有这样的数据集:

hive> describe logs;
 id string,
 ts string,
 app_id int

hive> select * from logs limit 5;
1389    2014-10-05 13:57:01 12
1656    2014-10-06 03:57:59 15
1746    2014-10-06 10:58:25 19
1389    2014-10-09 08:57:01 12
1656    2014-10-10 01:57:59 15

我的目标是获取过去3天的独特ID。最好的方法是读取当前系统时间并获取最近3天的唯一ID,但不确定我需要放置“unix_timestamp()”的位置。考虑到日志是实时记录的,并且今天是ts的日期,我试图使用这个查询(第一种方法)

hive > SELECT distinct id FROM logs HAVING to_date(ts) > date_sub(max(ts), 3) and to_date(ts) <  max(ts);
FAILED: SemanticException [Error 10025]: Line 1:45 Expression not in GROUP BY key 'ts'

如果我按下面的'ts'添加分组,则会出现此错误:

hive> SELECT distinct ext FROM pas_api_logs group by ts HAVING to_date(ts) > date_sub(max(ts), 7) and to_date(ts) <  max(ts);
FAILED: SemanticException 1:47 SELECT DISTINCT and GROUP BY can not be in the same query. Error encountered near token 'ts'

经过无数次尝试后,最后一种方法就是这样,在[类似主题] [1]之后研究。

Select distinct id from (SELECT * FROM logs JOIN logs ON (max(logs.ts) = to_date(logs.ts))
 UNION ALL
 SELECT * FROM logs JOIN logs ON (to_date(logs.ts) = date_sub(max(logs.ts), 1))
 UNION ALL 
 SELECT * FROM logs JOIN logs ON (to_date(logs.ts) = date_sub(max(logs.ts), 2)));

显然这也不起作用。有人可以对此有所了解吗?

1 个答案:

答案 0 :(得分:2)

使用此声明可获得所需结果:
从日志中选择不同的ID,其中DATEDIFF(from_unixtime(unix_timestamp()),ts)&lt; = 3;

希望它有所帮助!

相关问题