如何计算两个立即行之间的最大值差?

afdcj2ne  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(333)

我有一个表,它遵循以下结构:
表foo

id          number
---------------------
1             5
2             8
3             3
4             67
5             1
6             10

从这个表中,我想执行一个 SELECT 这显示了从一行到下一行增长最多的数字。在这个例子中,我想把它看作一个输出:

id          number
---------------------
4             67

因为上一行 id = 3 )有一个 number 的价值 3 ,下一行将值增加到 67 .
我该怎么做?

xqk2d5yq

xqk2d5yq1#

对示例数据执行此操作的一种方法是使用自联接:

select f1.*
from Foo f1 inner join Foo f2
on f2.id = f1.id - 1
order by f1.number - f2.number desc limit 1

如果id之间存在间隙,则必须找到每个id的前一个id,然后检索前一行中的编号:

select t.id, t.number
from (
  select f1.id, f1.number, max(f2.id) previd
  from Foo f1 inner join Foo f2
  on f2.id < f1.id
  group by f1.id, f1.number
) t inner join Foo f
on f.id = t.previd
order by t.number - f.number desc limit 1

或:

select f.*
from Foo f
order by number - (select number from Foo where id < f.id order by id desc limit 1) desc 
limit 1

对于mysql 8.0+,可以使用lag()窗口函数:

select *
from Foo
order by number - lag(number) over (order by id) desc limit 1

请看演示。

8gsdolmq

8gsdolmq2#

可能有漏洞,我使用的是mysql 5.7–user157629

SELECT t2.id, t2.num
FROM foo t1
JOIN foo t2 ON t1.id < t2.id
WHERE NOT EXISTS ( SELECT NULL
                   FROM foo t3
                   WHERE t1.id < t3. id
                     AND t3.id < t2.id )
GROUP BY t2.id, t2.num
ORDER BY t2.num - t1.num DESC, t2.id LIMIT 1;

如果有两对具有相同且最大的增长,那么最小的一行 id 将被退回。
小提琴

ycggw6v2

ycggw6v23#

也许是这样,但我想我把事情复杂化了

select * from (
    select n1.id as 'from' , n2.id as 'to', n2.number- n1.number as growth from 
 (  select @rownum := @rownum + 1 AS rownum, id, number from numbers
    join (select @rownum :=0) as r1
 ) as n1
 left join (
    select @rownum2 := @rownum2 + 1 AS rownum, id, number from numbers
    join (select @rownum2 :=0) as r2
    where id <> (select min(id) from numbers)
 ) as n2
 on n1.rownum = n2.rownum
) as mess

order by growth desc
limit 1

相关问题