2013-03-05 88 views
1

我想写一个hive查询,我对两个不同类型在同一个表中的关系感兴趣。例如,说我的表是建立这样的:Hive(或MySQL):使用最大时间戳查找不同类型的事件

event_type  timestamp    source 
completion  2013-03-04 12:00:55 NULL 
completion  2013-03-04 11:55:55 NULL 
impression  2013-03-04 11:53:45 A 
impression  2013-03-04 11:57:55 A 
impression  2013-03-04 11:58:00 B 

每完成,我想抓住最近一次展示的时间戳,以及它的来源。例如,我希望从上面的示例的查询中得出:

completion_timestamp most_recent_impression source 
2013-03-04 12:00:55  2013-03-04 11:58:00  B 
2013-03-04 11:55:55  2013-03-04 11:53:45  A 

任何提示?

回答

1

这依赖于时代的独特性。你应该添加一个ID列来解决这个问题。

子查询获取完成时间(i.ts < c.ts)之前的每个完成时间(GROUP BY c.ts)和最近的印象时间(MAX(i.ts))。

SELECT 
    completionTime, impressionTime, s.source 
FROM 
(SELECT 
    c.ts AS completionTime, MAX(i.ts) AS impressionTime 
FROM t AS c 
JOIN t AS i 
WHERE c.event_type = 'completion' 
AND i.event_type = 'impression' 
AND i.ts < c.ts -- impressions happen before completions 
GROUP BY c.ts) AS t2 
JOIN t AS s ON s.ts = t2.impressionTime 
ORDER BY completionTime DESC 

老好人SQLFiddle