postgresql-查找数据值小于前一行的行
我需要找到数据值小于前一行的行。最好的——下一排。我更喜欢使用单选查询而不是存储过程 数据样本:postgresql-查找数据值小于前一行的行,postgresql,Postgresql,我需要找到数据值小于前一行的行。最好的——下一排。我更喜欢使用单选查询而不是存储过程 数据样本: 1 3 5 8 7 6 10 11 16 15 14 13 所以我最好找到值为6的行。我可以修改表结构以添加任何必需的列。数据是从外部文件批量插入的,我可以完全控制这个过程。首先,您需要一些方法来对行进行排序。否则,无法判断哪一行是前一行 一旦有了排序列,就可以使用函数完成任务: postgres=# create table tbl(id serial, val numeric); CREATE
1
3
5
8
7
6
10
11
16
15
14
13
所以我最好找到值为6的行。我可以修改表结构以添加任何必需的列。数据是从外部文件批量插入的,我可以完全控制这个过程。首先,您需要一些方法来对行进行排序。否则,无法判断哪一行是前一行 一旦有了排序列,就可以使用函数完成任务:
postgres=# create table tbl(id serial, val numeric);
CREATE TABLE
postgres=# insert into tbl(val) values (1),(3),(5),(8),(7),(6),(10),(11),(16),(15),(14),(13);
INSERT 0 12
postgres=# select * from tbl order by id;
id | val
----+-----
1 | 1
2 | 3
3 | 5
4 | 8
5 | 7
6 | 6
7 | 10
8 | 11
9 | 16
10 | 15
11 | 14
12 | 13
(12 rows)
postgres=# select val
postgres-# from (
postgres(# select val, lag(val) over (order by id) prev_val
postgres(# from tbl
postgres(# ) t
postgres-# where val < prev_val;
val
-----
7
6
15
14
13
(5 rows)
关系数据库中的行没有排序,因此没有下一行或上一行的概念,除非您可以定义某种排序顺序。您只显示了一个未命名的列。你必须有一些列来定义这些值的排序顺序,否则就无法解决这个问题。我没有在这里添加它,以免干扰问题。