2015-03-31 15 views
0

這是我的數據表:如何獲取最新的行會在一定條件

sessionid | page | category | productid | time 
1   | detail | 3  | 4   | 20150303 1002 
1   | cart | null  | 4   | 20150303 1003 
2   | detail | 5  | 3   | 20150303 1005 
2   | detail | 5  | 3   | 20150303 1007 
2   | detail | null  | 2   | 20150303 1008 
2   | cart | null  | 3   | 20150303 1010 
2   | detail | 1  | 3   | 20150303 1013 

這是我的期望輸出

sessionid | page | category | productid | time   | refercategory 
1   | cart | null | 4   | 20150303 1003 | 3 
2   | cart | null | 3   | 20150303 1010 | 5 

基本上,我想看看只車事件,以及從事件之前的最近的詳細信息行中獲取類別字段,該字段具有非空類別值和相同的productid。因此,對於sessionid = 2的最後一個購物車事件,我會繼續上去,直到我用相同的sessionid(= 2),相同的productid(= 3)和非空類別值(= 5)擊中詳細信息頁面。

我試過加入(但不能限制到一個結果)和滯後(但無法正確過濾頁面)。我很感激關於這個令人困惑的問題的任何提示。謝謝!

回答

1

我不熟悉配置單元/ hiveql,所以我會回答一般的SQL。

select t1.sessionid, t1.page, t1.category, t1.productid, t1.time, t2.category as refercategory 
from table1 as t1 
join table1 as t2 on t1.sessionid = t2.sessionid and t1.productid = t2.productid 
where t1.page = 'cart' 
and t2.time = (select max(time) 
       from table1 as t3 
       where t3.sessionid = t2.sessionid and category is not null) 

下面是使用您的測試數據結果:

sessionid page category productid time   refercategory 
1   cart (null)   4  20150303 1003 3 
2   cart (null)   3  20150303 1010 5 

下面是一個小提琴顯示它的工作:http://sqlfiddle.com/#!9/38f7b0/4


編輯爲了配合修訂後的問題/數據I將查詢修改爲:

select t1.sessionid, t1.page, t1.category, t1.productid, t1.time, t2.category as refercategory 
from table1 as t1 
join table1 as t2 on t1.sessionid = t2.sessionid and t1.productid = t2.productid 
where t1.page = 'cart' 
and t2.time = (select max(time) 
       from table1 as t3 
       where t3.sessionid = t2.sessionid 
       and category is not null 
       and t3.time <= t1.time) 

唯一的變化是添加and t3.time <= t1.time以確保所選參考行的時間小於購物車行。

這裏是新的小提琴:http://sqlfiddle.com/#!9/a08ed/3

+0

嗨,感謝您的幫助!在這裏,我如何確保我拉取發生在購物車事件「之前」的詳細信息行? – magu2 2015-03-31 06:09:37

+0

澄清我已編輯最後一行的類別和時間。現在你的小提琴拉1作爲refercategory而不是我打算的5 .. – magu2 2015-03-31 06:12:03

+0

謝謝!這在SQL中很適用。我認爲唯一的問題是Hive不允許我在t2.time =()之後使用子查詢。任何解決方法? – magu2 2015-03-31 10:10:49