我正在尝试在Hive中执行查询。我有一个Item表,每个表都有多个与之关联的日期。我想检索每行的值与每行的前一个日期值之间的差异。
ID DATE VALUE
1 01-01-2014 10
1 03-01-2014 05
1 07-01-2014 40
1 05-01-2014 20
2 05-01-2014 10
我希望输出格式:
ID DATE VALUE
1 01-01-2014 10
1 03-01-2014 -5
1 05-01-2014 15
1 07-01-2014 20
2 05-01-2014 10
我尝试了以下查询。
SELECT C.ID ,C.DATE,C.VALUE AS CURRENT_DATE_VALUE,COALESCE(CAST(O.VALUE AS INT),0) AS PREV_DATE_VALUE,(C.VALUE-COALESCE(CAST(O.VALUE as INT),0)) AS DIFF_VALUE
FROM ITEM O
LEFT OUTER JOIN
( SELECT T.ID ,C.DATE,C.VALUE,MAX(UNIX_TIMESTAMP(T.DATE,'dd-MM-yyyy')) AS PREV_DATE
FROM ITEM C
LEFT OUTER JOIN ITEM T ON(C.ID = T.ID) WHERE
UNIX_TIMESTAMP (C.DATE,'dd-MM-yyyy') > UNIX_TIMESTAMP(T.DATE,'dd-MM-yyyy') GROUP BY
T.ID ,C.DATE,C.VALUE) C
ON (O.ID = C.ID AND UNIX_TIMESTAMP (O.DATE,'dd-MM-yyyy') = C.PREV_DATE)
此查询无法获取上一个日期没有行的行。任何人都可以使用自联接帮助我,因为我使用的是不支持窗口函数的hive版本?
任何帮助都将不胜感激。
答案 0 :(得分:0)
首先 - 创建表格,将数据加载到HIVE
use tmp ;
create table t_time(id string,td string,value int) row format delimited fields terminated by '\t' ;
LOAD DATA LOCAL INPATH '/home/hadoop/b.txt' INTO TABLE t_time;
第二 - 尝试以下SQL :(“if”是非常重要的方法)
select t1.id,t1.td,if(t2.td is null,t1.value,t1.value - t2.value)
from (
select a.id,a.td,max(if(b.td <a.td,b.td,null)) pre_td,a.value
from t_time a join t_time b
on (a.id = b.id)
group by a.id,a.td,a.value
) t1 left outer join t_time t2
on (t1.id = t2.id and t1.pre_td = t2.td)
结果
id td _c2
1 01-01-2014 10
1 03-01-2014 -5
1 05-01-2014 15
1 07-01-2014 20
2 05-01-2014 10