sql查询每个人最新的2个电话号码

表A中有客户电话号码信息与更新时间,如何查出客户最近更新的2个电话号码,如果客户只有一个电话号码,则号码1与号码2相同

A:

ID MOBILE UPDATE_DT UPDATE_TM
1 111 20180101 11:11:11
2 222 20180202 12:12:12
3 333 20180303 13:13:13
1 444 20180404 14:14:14
3 555 20180505 15:15:15
1 666 20180606 16:16:16

 结果:

ID MOBILE1 MOBILE2
1 666 444
2 222 222
3 555 333
select
    id
    ,mobile1
    ,coalesce(m2,m1) mobile2
from (
    select
        id
        ,max(case mobile_rank when '1' then mobile else '0' end) m1
        ,max(case mobile_rank when '2' then mobile else '0' end) m2
    from (
        select
            id
            ,mobile
            ,row_number() over(partition by id order by update_dt desc,update_tm desc) mobile_rank
        from A 
          ) b--查询出每个ID下的电话号码按更新时间倒排的序号,可能会有同一ID同一时间更新2个电话号码
   group by 1--每个ID取出排序最靠前的2个电话号码
   ) c

  

猜你喜欢

转载自www.cnblogs.com/king-cobra-rko/p/11167178.html