2014-10-19 43 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