SQL:如何在列中查找所有本地最小值

时间:2016-10-04 19:05:50

标签: sql

表A有2列:

id: integer auto increment primary key; 
value: integer 

通常记录有更大的" id"有更大的价值"列,但有时"值"专栏下来。我需要在"值"中找到所有具有局部最小值的记录。柱。

我知道如何使用光标并将当前记录与之前的记录进行比较。

我正在寻找纯SQL解决方案

SELECT id, value from A order by id
     id value
     -- -----
     1  10
     2  13
     3  9      <-- how to find this record
     4  14 
     5  25
     6  10     <-- how to find this record
     7  78

3 个答案:

答案 0 :(得分:0)

可以使用自我加入

select A.id, A.value, B.id, B.value from A 
left join b on a.id-1 = b.id and a..value >= b.value
where b.id is not null

答案 1 :(得分:0)

我建议使用ANSI标准lag()函数:

select a.*
from (select a.*, lag(value) over (order by id) as prev_value
      from a
     ) a
where prev_value > value;

如果您对局部最小值的定义是它小于前一个和下一个值:

select a.*
from (select a.*,
             lag(value) over (order by id) as prev_value,
             lead(value) over (order by id) as next_value
      from a
     ) a
where value < prev_value and
      (value > next_value or next_value is null);

注意:您可能需要<=(等),具体取决于您的定义。

答案 2 :(得分:0)

我已经完成了,

从table_name中选择id,value,其中1!= 2,rownum = 1 order by value;

这里'rownum'只是简单的索引,我已经显示了第一条记录