如何选择Hi​​ve分区中每列的最后NON-NULL值

时间:2014-09-17 14:28:56

标签: sql hive partition windowing

我有一个包含表单事务数据的hive表(高度简化)

id  Status  Value   UpdatedTimeStamp

515 Open    1   2014-05-08T11:43:27
516 Open    NULL    2014-05-08T11:43:27
515 Answered    1   2014-05-09T11:43:27 
515 Closed  NULL    2014-05-10T11:43:27
517 Open    NULL    2014-05-09T11:43:27
516 Closed  NULL    2014-05-09T11:43:27

对于我的用例,我需要一个包含唯一ID的输出表,其中列条目是按时间戳排序时该列中该特定id的最后一个非NULL值。

因此,所需的输出是:

id  Status  Value   UpdatedTimeStamp

515 Closed  1   2014-05-10T11:43:27
516 Closed  NULL    2014-05-09T11:43:27
517 Open    NULL    2014-05-09T11:43:27

我试图通过在分区上使用窗口函数来实现这一点

INSERT OVERWRITE TABLE testSample2 SELECT id, FIRST_VALUE (Status) OVER SortedData, FIRST_VALUE (Value IGNORE NULLS) OVER SortedData, FIRST_VALUE (UpdatedTimeStamp) OVER SortedData FROM testSample WINDOW SortedData (PARTITION BY id ORDER BY UpdatedTimeStamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING);

这给了我NullPointerException(可能,Hive尚不支持IGNORE NULLS)。请建议我如何获取最后一个非NULL值。

1 个答案:

答案 0 :(得分:1)

尝试使用以下内容:

select ss.vl1, FIRST_VALUE(ss.ky) OVER (PARTITION BY ss.vl1 ORDER BY ss.nl, ss.vl rows unbounded preceding) 
FROM (
    SELECT IF(s.vl=123456, 'sasa', 'AAAAAA') as vl1, s.vl, s.ky, IF(s.ky IS NULL, 1, 0) as nl
    FROM (
        select explode(map(NULL, 123, 1, 1234, 2, 12345, 3, 123456)) as (ky, vl) from default.dual) s ) ss;
vl1     _wcol0
AAAAAA  1
AAAAAA  1
AAAAAA  1
sasa    3