比较记录到postgresql中的前一个记录

w7t8yxp5  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(148)

我在PostgreSQL DB中有一个这样的表:

Client | Rate | StartDate|EndDate     
 A      | 1000 | 2005-1-1 |2005-12-31
 A      | 2000 | 2006-1-1 |2006-12-31
 A      | 3000 | 2007-1-1 |2007-12-31  
 B      | 5000 | 2006-1-1 |2006-12-31  
 B      | 8000 | 2008-1-1 |2008-12-31  
 C      | 2000 | 2006-1-1 |2006-12-31

如何得到这个结果?

Client | Rate | StartDate|EndDate    |Pre Rate | Pre StartDate |Pre EndDate    
 A      | 1000 | 2005-1-1 |2005-12-31 |         |               |             
 A      | 2000 | 2006-1-1 |2006-12-31 | 1000    | 2005-1-1      |2005-12-31            
 A      | 3000 | 2007-1-1 |2007-12-31 | 2000    | 2006-1-1      |2006-12-31  
 B      | 5000 | 2006-1-1 |2006-12-31 |         |               |              
 B      | 8000 | 2008-1-1 |2008-12-31 | 5000    | 2006-1-1      |2006-12-31   
 C      | 2000 | 2006-1-1 |2006-12-31
2hh7jdfx

2hh7jdfx1#

SELECT client, 
       rate,
       startdate, 
       enddate, 
       lag(rate) over client_window as pre_rate,
       lag(startdate) over client_window as pre_startdate,
       lag(enddate) over client_window as pre_enddate
FROM the_table
WINDOW client_window as (partition by client order by startdate)
ORDER BY client, stardate;

这假定同一行的enddate总是大于startdate,并且没有enddate大于后面的startdate

相关问题