我在 table 上记录了 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
我该怎么做。
最佳答案
这是一种方法,使用相关子查询来获取先前的信息:
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)
上建立索引。
关于mysql - SQL复杂的select语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26453736/