Select 最后一行基于重置前增加的列值?

Select last rows based on increasing column value before reset?

我尝试编写一个 (postgres) sql 查询,其中 returns 特定数字列之前的最后一行低于它的前值,对于多个 services.

假设给定的数据如下:

service | captured | online_seconds
--------+----------+---------------
A       | 01:10:00 | 500 <--
A       | 01:08:00 | 100
A       | 01:07:00 | 600 <--
A       | 01:02:00 |  50
B       | 01:09:00 | 400 <--
B       | 01:06:00 | 200
B       | 01:05:00 | 700 <--

预期结果为:

service | captured | online_seconds
--------+----------+---------------
A       | 01:10:00 | 500
A       | 01:07:00 | 600
B       | 01:09:00 | 400
B       | 01:05:00 | 700

SQL Fiddle: https://www.db-fiddle.com/f/9jZiSLa5L9tCD7pmXwFiYW/1

直到现在我都找不到任何解决方案,如果可能的话,有什么想法可以实现吗?

根据您的数据,您想查看该服务的前一个值的值增加的位置。为此,使用 lag():

select t.*
from (select t.*,
             lag(online_seconds) over (partition by service order by captured) as prev_online_seconds
      from t
     ) t
where online_seconds > prev_online_seconds

使用LEAD查看下一行的数据:

select service, captured, online_seconds
from
(
  select
    service,
    captured,
    online_seconds,
    lead(online_seconds) over (partition by service order by captured) as next_online_seconds
  from mytable
) with_next_online_seconds
where next_online_seconds < online_seconds or next_online_seconds is null
order by captured;