s Date Kilometer
B3 2017-02-03 23332
B4 2017-02-10 23475
B5 2017-02-12 23875
B6 2017-02-14 24175
B7 2017-02-18 24875
B8 2017-02-24 25125
B9 2017-02-27 25775
Total (SUM) 2443
=((B4-B3)+(B5-B4)+(B6-B5)+(B7-B6)+(B8-B7)+(B9-B8)),
我希望使用Mysql这个总和。
答案 0 :(得分:0)
首先根据s
列的顺序给出一个行号。然后使用此结果集并将其与自身连接。
<强>查询强>
set @rn := 0;
select (t1.`kilometer`) - (t2.`kilometer`) `km` from(
select @rn := @rn + 1 as `rn`, `s`, `date`, `kilometer`
from `your_table_name`
order by length(`s`), `s`
)t1
join (
select @rn := @rn + 1 as `rn`, `s`, `date`, `kilometer`
from `your_table_name`
order by length(`s`), `s`
)t2
on t1.`rn` = t2.`rn` - 1;