2014-10-19 44 views
0

我有表,我記錄汽車#,日期,RunHours波紋管:SQL複雜的SELECT statment

Car#  Date   RunHours 
125  2014-01-01  1250 
125  2014-02-10  3250 
215  2014-02-11  1400 
215  2014-03-01  1800 
125  2014-03-15  4100 
215  2014-04-10  2500 

我需要選擇結果作爲波紋管:

Car#  Date  Runhours Previous_Date  Previous_RunHours 
125  2014-01-01  1250   N/A    N/A 
125  2014-02-10  3250  2014-01-01   1250 
215  2014-02-11  1400   N/A    N/A 
215  2014-03-01  1800  2014-02-11   1400 
125  2014-03-15  4100  2014-02-10   3250 
215  2014-04-10  2500  2014-02-11   1800 

我該怎麼辦它。 謝謝。

+0

最後一行中的Previous_Date應該是2014-03-01,對嗎? – Crowcoder 2014-10-19 18:12:01

回答

0

這裏有一個方法,使用相關子查詢來獲得以前的信息:

select t.*, 
     (select t2.date 
     from table t2 
     where t2.car = t.car and t2.date < t.date 
     order by t2.date desc 
     limit 1 
     ) as prev_date, 
     (select t2.runhours 
     from table t2 
     where t2.car = t.car and t2.date < t.date 
     order by t2.date desc 
     limit 1 
     ) as prev_runhours 
from table t; 

出於性能考慮,你想對table(car, date)的索引。

+0

檢查,我會反饋 – user2692907 2014-10-21 13:28:12