SQL Complex选择语句?

时间:2014-10-19 18:07:43

标签: mysql date

我在桌子上,我记录Car#,Date,RunHours如下:

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

我该怎么做。

1 个答案:

答案 0 :(得分: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)上的索引。