Postgresql - 选择相应的Lead列

时间:2018-01-08 16:56:07

标签: sql postgresql

我可以使用

找到每行的 潜在客户状态日期
select lead(status_date) OVER(ORDER BY dept_id, status_date, id) as "lead_date" from my_table

如何获得相应的 潜在客户状态 ,其顺序与 潜在客户状态日期 相同?

id, dept_id, status, statud_date
---------------------------------
1   001      OPEN    1/1/2017
2   001      ACTIVE  2/2/2017
3   002      CLOSED  1/15/2017

1 个答案:

答案 0 :(得分:1)

您将参数更改为lead()

select lead(status_date) OVER (ORDER BY dept_id, status_date, id) as next_status_date,
       lead(status) OVER (ORDER BY dept_id, status_date, id) as next_status      
from my_table;

通常情况下,我希望部门状态,所以我认为这就是你想要的:

select lead(status_date) OVER (partition by dept_id ORDER BY status_date, id) as next_status_date,
       lead(status) OVER (partition by dept_id ORDER BY status_date, id) as next_status      
from my_table;

如果使用同一子句有多个窗口规范,则可以指定一次子句:

select lead(status_date) over w as next_status_date,
       lead(status) over w as next_status      
from my_table
window w as (partition by dept_id order by status_date, id) ;