MySQL表中的累积到差异数据

时间:2014-07-21 05:25:49

标签: mysql sql date

我有一张桌子作为

+-----------+--------+------------+-------------+
| taxino    | driver | allotdate  | returndate  |
+-----------+--------+------------+-------------+
| 31032     | John   | 2014-06-13 | 2014-06-15  | 
| 31032     | John   | 2014-06-18 | NULL        |
| 40001     | John   | 2014-01-01 | 2014-06-01  |
| 40001     | Alice  | 2014-06-15 | NULL        |
| 40002     | Alice  | 2014-05-17 | 2014-06-18  |
| 40003     | Robin  | 2014-06-17 | 2014-06-18  |
+-----------+--------+------------+-------------+

此表显示出租车被分配给司机时,返回列中的NULL表示出租车未归还。
我有一个距离报告表

+------------+---------+------------+-----+
|  taxi    | reportdate | distance_in_km  |
+------------+---------+------------+-----+
| 40001   | 2014-04-30 |              527 |
| 40001   | 2014-05-26 |             1497 |
| 40002   | 2014-04-30 |             1414 |
| 40002   | 2014-05-26 |             2796 |
| 40003   | 2014-04-22 |              392 |
| 40003   | 2014-05-26 |             1663 |
+------------+---------+------------+-----+

这里的距离是累积的,也就是说,在下一个报告中添加了前一个报告日期的行进距离。使用这些表我想知道哪个司机开出租车多久,无论他开的是哪辆出租车。如下图所示:

Driver | date | distance_traveled_by_driver

此处distance_traveled_by_driver不是累积的,也就是说,它包含两个报告日期之间的距离。请帮我这样做。

1 个答案:

答案 0 :(得分:1)

此查询显示自上次报告日期以来的距离

select driver, reportdate, distance_since_last from (
    select t1.driver, 
    t2.reportdate,
    if(@prevTaxi = t2.taxi,
        t2.distance_in_km - @prevDistance,
        t2.distance_in_km) distance_since_last,
    @prevTaxi := t2.taxi,
    @prevDistance := t2.distance_in_km
    from table1 t1
    join table2 t2 on t1.taxino = t2.taxi
    cross join (select @prevDistance := 0, @prevTaxi := 0) t3
    order by taxi, reportdate
) t1