2015-03-31 17 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