Y
Y
Yuri2018-05-01 14:49:25
MySQL
Yuri, 2018-05-01 14:49:25

How can mysql query calculate the difference between the numbers of the two nearest rows in a column?

table `nspcl`
----------
id | partnum
----------
1 | 7079626
2 | 7079623
3 | 7079593
4 | 7079552
.....
you need to calculate the difference between the nearest ones from the end, i.e.
7079552 - 7079593 = -41
7079593 - 7079623 = -30
7079623 - 7079626 = -3
is it possible to implement this with a mysql query?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
idShura, 2018-05-01
@elcity

Can be done with window functions

SELECT partnum,
       LAG(partnum) OVER w AS 'prev_partnum',
       partnum - LAG(partnum)  OVER w AS 'diff' 
  FROM nspcl
WINDOW w AS (ORDER BY id);

D
Dimonchik, 2018-05-01
@dimonchik2013

"two ends, two rings, in the middle - a carnation" - "the glasses were nailed to the fraer"

you can count, only the muscle does not know anything about the ends, so the request needs an ordered sequence (well, go for an autoincrement) and three-story expressions
with a competent ID can be shorter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question