【问题标题】:building historic table in hiveql with expiredate在具有过期日期的 hiveql 中构建历史表
【发布时间】:2017-05-15 08:58:34
【问题描述】:

我需要根据表构建某种历史记录 带有id和日期

每个日期都标志着一个变化,最新的日期是 主动一,

table

historic_trans
id  trans_date  
22  20170510 
22  20170502 
22  20170412

我想建立一个历史表,其中最新的行 通过将过期列添加为“99991231”来获得活跃标记

我可以通过

轻松找到活跃的
select id, max(trans_date)trans_date, '99991231' as Expiredate, 'yes' as active
from historic_trans 
where id = '22'
group by id

但我确实需要在前一行设置设置 trans_date 在我的非活动行中

id  trans_date   Expiredate active 
22  20170510    99991231    yes
22  20170502    20170510    no
22  20170412    20170502    no 

这样过期日期就反映了交易的变化

可以在纯hql/sql中完成吗

我一直在玩下面的代码,但我被困在里面了

select historic_trans.id, historic_trans.trans_date,
    case when aktiv.Expiredate = '99991231' then aktiv.Expiredate
     else aktiv.Expiredate
    end as Expiredate
 from historic_trans 
 left outer join 
(
 select id, max(trans_date)trans_date, '99991231' as Expiredate, 'yes' as active
    from historic_trans 
    where id = '22' 
 group by id
) aktiv on aktiv.id = historic_trans.id and aktiv.trans_date =   historic_trans.trans_date
 where historic_trans.id = '22'  

有什么建议吗?

【问题讨论】:

  • 有什么理由不使用date 类型或至少ISO 日期格式-yyyy-MM-dd
  • 好吧,只要收到数据,我就可以用另一种格式指定 ExpireDate 了。

标签: hive hiveql


【解决方案1】:
select  id
       ,trans_date
       ,lag (trans_date,1,date '9999-12-31') over w                     as Expiredate
       ,case when row_number () over w = 1 then 'yes' else 'no' end     as active

from    historic_trans

window  w as (partition by id order by trans_date desc)
;

+----+------------+------------+--------+
| id | trans_date | expiredate | active |
+----+------------+------------+--------+
| 22 | 2017-05-10 | 9999-12-31 | yes    |
| 22 | 2017-05-02 | 2017-05-10 | no     |
| 22 | 2017-04-12 | 2017-05-02 | no     |
+----+------------+------------+--------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 2016-08-27
    • 2015-06-29
    • 2014-05-16
    • 1970-01-01
    • 2023-03-28
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多