PL/SQl,oracle 9i,使用sql删除重复行
我们这里有一个场景,我们需要根据时间戳从表中删除所有重复行。表结构如下所示:
Item Ref1 Ref2 Timestamp 1 A test1 2/3/2012 10:00:00 1 A test2 2/3/2012 11:00:00 1 A test1 2/3/2012 12:00:00 2 A prod1 2/3/2012 10:00:00 2 B prod2 2/3/2012 11:00:00 2 A prod2 2/3/2012 12:00:00
因此我们需要根据 item 和 ref1 删除该表中的重复行。像这里一样,我们应该只有 1 行用于项目 1 和具有最新时间戳的 ref1 A。对于第 2 项,我们应该只有 1 行具有最新时间戳的 ref1 A。
任何指点都会很棒
we have a scenario here where we need to delete all the duplicate rows from a table based on timestamp. The table structure looks like this:
Item Ref1 Ref2 Timestamp 1 A test1 2/3/2012 10:00:00 1 A test2 2/3/2012 11:00:00 1 A test1 2/3/2012 12:00:00 2 A prod1 2/3/2012 10:00:00 2 B prod2 2/3/2012 11:00:00 2 A prod2 2/3/2012 12:00:00
So we need to delete the duplicate rows from this table based on item and ref1. like here we should have only 1 row for item 1 and ref1 A with the latest timestamp. Same for item 2 we should have only 1 row for ref1 A with latest timestamp.
Any pointers will be great
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您想要的最终结果是一个包含这 3 行的表格,
假设
没有两行具有相同的
Item
和Ref1
且两者都具有相同的 <代码>时间戳。如果可以有多个行具有相同的Item
和Ref1
,并且它们都具有最新的Timestamp
并且假设您不关心哪一行保持Assuming that your desired end result is a table with these 3 rows
Something like
should work assuming that there are no two rows with the same
Item
andRef1
that both have the sameTimestamp
. If there can be multiple rows with the sameItem
andRef1
that both have the latestTimestamp
and assuming that you don't care which one you keep您可以查询按 Item 和 Ref1 分组的记录,然后删除 Item 和 Ref 相等且 Timestamp < 的记录。最大限度。
有了结果...
You can query your records grouping by Item and Ref1 an then delete where Item and Ref are equals and Timestamp < max.
With the results...
我手头没有安装 Oracle 9,因此无法对此进行测试,但我相信这可能有效:
创建一个视图,其中列出了向您的记录添加“索引”的内容:
SELECT ROW_NUMBER( ) OVER (PARTITION BY Item, Ref1 ORDER BY Timestamp DESC) ix, * FROM table
删除视图中
ix
大于 1 的记录I don't have an Oracle 9 install at hand, so I cannot test this, but I believe that this may work:
Create a view which lists adds "indices" to your records:
SELECT ROW_NUMBER( ) OVER (PARTITION BY Item, Ref1 ORDER BY Timestamp DESC) ix, * FROM table
Delete the records from the view where
ix
is higher than 1