2012-02-01 56 views
7

我有這樣的PostgreSQL的數據庫表:比較記錄此前的紀錄在PostgreSQL的

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 

非常感謝!

回答

9
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; 

這是假設結束日期是沒有結束日期比下面的開始日期

+0

這一個偉大的工程大於從同一行,並且開始日期總是更大。謝謝。 – Alex 2012-02-02 13:38:09

+0

'WINDOW client_window'別名很好,注意到一個 – Davos 2017-11-13 09:56:25