减去当前的旁边,并将该输出作为当前行的数据

时间:2018-03-23 08:06:39

标签: mysql sql

计算公里运行基于此

current value = next value - current value

我有一张看起来像这样的表。

enter image description here

我的问题是如何根据里程表值计算kmr?我将替换kmr值的kmr列的值

2 个答案:

答案 0 :(得分:3)

您可以使用变量存储最后的值。

create table tbl (code varchar(10), vdate date, kmr int);
insert into tbl values
('Person1', '20180101', 71883),
('Person1', '20180102', 71893),
('Person1', '20180103', 71903),
('Person2', '20180101', 71800),
('Person2', '20180102', 71815),
('Person2', '20180103', 71820);
select code, vdate, kmr, current_kmr
from
(
  select t1.code, t1.vdate, t1.kmr, 
         t1.kmr - if(coalesce(@last_code, t1.code) = t1.code, coalesce(@last_kmr, t1.kmr), t1.kmr)  as current_kmr,
         @last_kmr := t1.kmr,
         @last_code := t1.code
  from   tbl t1,
         (select @last_kmr := null, @last_code := null) t2
  order by t1.code, t1.vdate
) t
code    | vdate      |   kmr | current_kmr
:------ | :--------- | ----: | ----------:
Person1 | 2018-01-01 | 71883 |           0
Person1 | 2018-01-02 | 71893 |          10
Person1 | 2018-01-03 | 71903 |          10
Person2 | 2018-01-01 | 71800 |           0
Person2 | 2018-01-02 | 71815 |          15
Person2 | 2018-01-03 | 71820 |           5

dbfiddle here

答案 1 :(得分:1)

这将使用排名和超过一个人

  

pop

Select m.`code`,m.vdate, ( n.kmr - m.kmr) as new_kmr
From
(Select t1.*, @rnk := @rnk + 1 as rnk
From tbl t1, (select @rnk := 0) t
Order by t1.`code`,t1.vdate) m left join
(Select t2.*, @rnk1 := @rnk1 + 1 as rnk
From tbl t2, (select @rnk1:= 0) t
Order by t2.`code`,t2.vdate) n
On m.`code` = n.`code`
And m.rnk + 1 = n.rnk 
Order by m.`code`, m.vdate

<强>输出:

code            vdate          new_kmr
person 1    2018-03-01  10
person 1    2018-03-02  10
person 1    2018-03-03  (null)
person 2    2018-03-01  5
person 2    2018-03-02  (null)