如何在Postgresql中找到下次访问?

时间:2018-06-14 14:38:39

标签: postgresql

我有一个名为visit_record的表:

customer_id visit_month
000001      1
000001      3
000001      7
000001      8
000002      2
000002      3
      ...

我想输出以下内容:

customer_id visit_month next_visit
    000001      1       3
    000001      3       7
    000001      7       8
    000001      8       null
    000002      2       3
    000002      3       5
               ...

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用lead() window function

select customer_id, 
       visit_month,
       lead(visit_month) over (partition by customer_id order by visit_month) as next_visit
from visit_record
order by customer_id, visit_month;