[英]SQL - Selecting rows with a column value greater than the rows before it
I'm curious on the best way to write a query. 我很好奇编写查询的最佳方法。
I have a table of ids and values. 我有一个ID和值表。 I would like to exclude rows where val is less than val in all of the rows with a lower ID.
我想排除ID较低的所有行中val小于val的行。
I was playing with joining this table to itself on id-1 but that didn't work all of the time. 我当时正在将这张桌子与ID-1上的桌子相连,但这并不是一直都有效。
Some sample data 一些样本数据
CREATE TEMP TABLE new_temp_table (
id integer,
val integer
);
INSERT INTO new_temp_table (id, val)
VALUES (0, 300),
(1, 150),
(2, 100),
(3, 200),
(4, 320),
(5, 120),
(6, 220),
(7, 340);
I want the following output. 我想要以下输出。
--- id --- val
--- 0 --- 300
--- 4 --- 320
--- 7 --- 340
Any help/direction would be appreciated. 任何帮助/方向将不胜感激。
From what you describe, you can use window functions to calculate the max on all the preceding rows and then filter based on that: 根据您的描述,您可以使用窗口函数来计算前面所有行的最大值,然后根据该值进行过滤:
select id, val
from (select ntt.*, max(val) over (order by id rows between unbounded preceding and 1 preceding) as preceding_max
from new_temp_table ntt
) t
where preceding_max is null or val > preceding_max;
Here is a db<>fiddle. 这是db <>小提琴。
Note: It is tempting to write this logic without the window specification as: 注意:在没有窗口规范的情况下编写此逻辑很诱人:
select id, val
from (select ntt.*, max(val) over (order by id) as preceding_max
from new_temp_table ntt
) t
where preceding_max is null or val >= preceding_max;
However, this will return rows where the max equals an earlier maximum. 但是,这将返回最大等于更早的最大值的行。
I would do: 我会做:
select
id, val, max_prev_val
from (
select
id,
val,
max(val) over(order by id rows between unbounded preceding and 1 preceding)
as max_prev_val
from new_temp_table
) x
where val >= max_prev_val or max_prev_val is null
Result: 结果:
id val max_prev_val
----------------------------------------
0 300 <null>
4 320 300
7 340 320
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.