如何调用 where 子句中的前一行?
How do you call previous row in a where clause?
我正在尝试弄清楚如何消除相邻出现的结果。例如,行具有创建时间戳 (source_time)。我想删除彼此相隔 10 秒内出现的结果。
我认为 lag() 可能会这样做,但我不能在 where 子句中使用它。
select *
from table
where source_time - previous(source_time) >= 10 second
很粗糙的代码,但是不知道怎么调用之前的源码时间。我已将它们转换为时间戳并使用 timestamp_diff(source_time, x, second) >= 10 但不确定如何使 x 成为先前的值。
希望这是清楚的。
您可以使用子查询来做到这一点。
delete table t1
where t1.id in (
select t2.id
from (
select
id,
source_time - lag(source_time) over (order by source_time) as time_diff
from table
) t2
where t2.time_diff < 10 second
)
请记住,这可能会在您的记录中留下很大的空白。例如,如果您在一个小时内每 9 秒获得一行,您将删除该小时内除最后一条记录以外的所有记录。
您可以改为每 10 秒对 source_time 进行分区,并删除 row_number > 1 的任何内容。
delete table t1
where t1.id in (
select t2.id
from (
select
id,
source_time,
row_number() over(
partition by source_time - make_interval(second => extract(second from source_time) % 10)
order by source_time asc
) rownum
from table
) t2
where rownum > 1
)
我正在尝试弄清楚如何消除相邻出现的结果。例如,行具有创建时间戳 (source_time)。我想删除彼此相隔 10 秒内出现的结果。
我认为 lag() 可能会这样做,但我不能在 where 子句中使用它。
select *
from table
where source_time - previous(source_time) >= 10 second
很粗糙的代码,但是不知道怎么调用之前的源码时间。我已将它们转换为时间戳并使用 timestamp_diff(source_time, x, second) >= 10 但不确定如何使 x 成为先前的值。
希望这是清楚的。
您可以使用子查询来做到这一点。
delete table t1
where t1.id in (
select t2.id
from (
select
id,
source_time - lag(source_time) over (order by source_time) as time_diff
from table
) t2
where t2.time_diff < 10 second
)
请记住,这可能会在您的记录中留下很大的空白。例如,如果您在一个小时内每 9 秒获得一行,您将删除该小时内除最后一条记录以外的所有记录。
您可以改为每 10 秒对 source_time 进行分区,并删除 row_number > 1 的任何内容。
delete table t1
where t1.id in (
select t2.id
from (
select
id,
source_time,
row_number() over(
partition by source_time - make_interval(second => extract(second from source_time) % 10)
order by source_time asc
) rownum
from table
) t2
where rownum > 1
)