2014-10-10 588 views
1

在SQL中看起來很簡單,但我在使用HiveQL時遇到了日期範圍的問題。HiveQL,Hive SQL選擇日期範圍

我有一個數據集是這樣的:

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 

我的目標是讓不同的ID的最後3天。最好的辦法是讀取當前系統時間並獲取最近3天的唯一標識,但不知道需要放置「unix_timestamp()」的位置。認爲該日誌記錄的實時性和有今天的TS日期,我想如果我通過「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' 

,它吐出了這個錯誤:

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))); 

顯然這也不起作用。有人可以解釋一下這個問題嗎?

回答

2

所需的結果可以通過使用該語句來獲得:
選擇從日誌不同id其中DATEDIFF(FROM_UNIXTIME(UNIX_TIMESTAMP()),TS)< = 3;

希望它有幫助!

+0

非常感謝你!!!! – user1486507 2014-11-06 21:54:04

+0

如果你有一段時間請幫我解決這個問題。謝謝。 http://stackoverflow.com/questions/25982081/receiving-exception-while-selecting-data-from-bucket-in-hive – Ajaykishan 2014-11-07 01:40:23

+0

另外,如果有人感到慷慨,我提出了一個類似的問題,可以使用一些幫助:http ://stackoverflow.com/questions/33324375/how-do-you-get-event-date-current-date-10-days-in-hiveql – 2015-10-26 02:38:45