return前后值较低的行

return the row where before and after value is lower

我有一个 table 看起来像这样:

name         val
1            1
2            2
3            1
4            2
5            2
6            10

对于每一行,我想检查该值与上一个值相比是否有所增加。然后,我想 return 上一个和下一个值较低的行。例如,在这种情况下,我想 return

name         val
2            2

但不是以下任何一项:

4            2
5            2
6            10

因为在 table 结束之前一直在增加,并且在结束时没有减少。理想情况下,我还想在开始比较 val.

之前按 namecol 订购 table

您可以像下面这样使用前导和滞后函数编写查询

解释:

因此,lag 从前一行获取 Val 列的数据,而 lead 从下一行获取数据

我们添加了一个 case 语句来处理第一行滞后数据和最后一行超前数据的空值。 要了解有关超前滞后函数的更多信息,请阅读此 link

select name, val 
from 
(select *,
 CASE WHEN LAG(val) OVER( ORDER BY name) IS NULL THEN 
val ELSE LAG(val) OVER( ORDER BY name) END as prev_value,
    CASE WHEN LEAD(val)  OVER( ORDER BY name) IS NULL THEN val ELSE LEAD(val)  OVER( ORDER BY name) END as next_value
    from yourtable 
    )T
    where prev_value<val AND val> next_value

使用默认值

select name, val 
from 
(select *,
 LAG(val,1,val) OVER( ORDER BY name) as prev_value,
 LEAD(val,1,val) OVER( ORDER BY name) as next_value
    from yourtable 
    )T
    where prev_value<val AND val> next_value