我遇到了一个问题,即有一个历史表每天提取一个表,并给它一个时间戳。不幸的是,数据在过去每天加载多次,这不应该。
就像:
- 时间戳/id
- 2020年7月13日15:01…/123
- 2020年7月13日15:02…/123
- 2020年7月13日15:03…/123
- 2020年7月14日15:01…/123
- 2020年7月14日15:02…/123
- 2020年7月14日15:03…/123
应该像:
- 2020年7月13日15:01…/123
- 2020年7月14日15:01…/123
我正在寻找一种方法,根据每天的第一个时间戳删除重复项。
你有什么想法用这种方式删除重复的吗?
提前谢谢!
我建议使用CTE:进行删除
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY id, CONVERT(date, ts_col) ORDER BY ts_col) rn
FROM yourTable
)
DELETE
FROM cte
WHERE rn > 1; -- targets all records per day except for the first one
如果只有两列,请使用聚合:
select id, cmin(timestamp) as timestamp
from t
group by id, convert(date, timestamp);
如果您有很多列,并且想要完整的行,那么row_number()
可能是最好的选择:
select t.*
from (select t.*,
row_number() over (partition by id, convert(date, timestamp) order by timestamp) as seqnum
from t
) t
where seqnum = 1;
您可以使用此选择来控制:
select a.* from yourtable a
inner join
(
select id,convert(date,[datetime]) [date], MIN([datetime]) [datetime]
from yourtable
group by id,convert(date,[datetime])
) b on a.id = b.id and convert(date,a.[datetime]) = b.[date] and a.[datetime] <> b.[datetime]
并删除:
delete a from yourtable a
inner join
(
select id,convert(date,[datetime]) [date], MIN([datetime]) [datetime]
from yourtable
group by id,convert(date,[datetime])
) b on a.id = b.id and convert(date,a.[datetime]) = b.[date] and a.[datetime] <> b.[datetime]