删除除了每个时间间隔组内的前N行之外的所有行。

huangapple go评论65阅读模式
英文:

Delete all rows except first N rows within each time interval group

问题

我有一张表:

ID DateTime
1 2022-01-30 01:02:03
1 2022-01-30 01:34:03
1 2022-01-30 02:59:03
2 2022-01-30 01:02:03
2 2022-01-30 01:34:03
2 2022-01-30 02:59:03

我想要删除除了每个唯一ID的每个小时之外的所有行。因此,结果表将如下所示:

ID DateTime
1 2022-01-30 01:02:03
1 2022-01-30 02:59:03
2 2022-01-30 01:02:03
2 2022-01-30 02:59:03
英文:

I have a table:

ID DateTime
1 2022-01-30 01:02:03
1 2022-01-30 01:34:03
1 2022-01-30 02:59:03
2 2022-01-30 01:02:03
2 2022-01-30 01:34:03
2 2022-01-30 02:59:03

And I would like to delete all the rows except for 1 every hour for each unique ID. So the resulting table would look like:

ID DateTime
1 2022-01-30 01:02:03
1 2022-01-30 02:59:03
2 2022-01-30 01:02:03
2 2022-01-30 02:59:03

答案1

得分: 3

你可以使用通用表表达式 (CTE) 和窗口函数:

with cte as (
    select *, row_number() over (
         partition by id, cast(datetime as date), datepart(hour, datetime)
         order by datetime
    ) as rn
    from t
)
select * -- delete
from cte
where rn > 1

一旦确认查询包含正确的行,请将select *更改为delete

英文:

You can use a cte (they could be used for delete) and window functions:

with cte as (
    select *, row_number() over (
         partition by id, cast(datetime as date), datepart(hour, datetime)
         order by datetime
    ) as rn
    from t
)
select * -- delete
from cte
where rn > 1

Change select * to delete once you're sure that the query contains the correct rows.

huangapple
  • 本文由 发表于 2023年2月9日 03:05:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定