如何从蜂巢中的记录中获取第二个最后日期?

时间:2016-12-20 03:07:30

标签: sql hive

我有一张这样的表:

    member        dato
    696382      2016-06-21
    35546232    2016-02-01
    9001107     2013-09-23
    40310785    2014-07-18
    3802508     2015-06-21
    74376545    2016-01-11
    14969202    2014-12-08
    17495001    2015-09-01
    17238917    2016-11-16

dato是会员购买2015-01-01至昨天的产品的日期。我想得到一个包含三列的新表:member,dato,dato_second。 dato_second是最接近dato的日期。例如,17238917在历史上有三个数据,附加于2016-11-16' 2016-11-10' 2015-03-27' 2015-03-27&#39 ;,新纪录将是17238917,2016-11-16' 2016-11-10'。那么如何获得新表呢?

2 个答案:

答案 0 :(得分:1)

嗯。我认为条件聚合和row_number()是最简单的解决方案:

select member,
       max(case when seqnum = 1 then dato end) as dato,
       max(case when seqnum = 2 then dato end) as dato_1
from (select t.*,
             row_number() over (partition by member order by dato desc) as seqnum
      from t
     ) t
group by member;

答案 1 :(得分:1)

这就是你要找的东西

select  member
       ,dato
       ,lag (dato) over (partition by member order by dato) as prev_dato            

from   mytab