SQL Complex选择语句?

问题描述 投票:0回答:1

我有桌子,我记录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

我该怎么做。

mysql date
1个回答
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)上的索引。

© www.soinside.com 2019 - 2024. All rights reserved.