【问题标题】:Oracle: Delete older records keeping newest n records for users based on Created_On timestampOracle:删除旧记录,根据 Created_On 时间戳为用户保留最新的 n 条记录
【发布时间】:2016-08-12 13:45:05
【问题描述】:

我在 Oracle 11g 中有一个表,其中包含不同用户的多条记录,我想从表中删除多余的旧记录,并只为特定用户保留 5 条最新记录。

示例: 考虑下表屏幕截图,其中包含用户“JACK”、“ANGEL”、“MACK”的多条记录,我必须为每个基于列“CREATED_ON”的新用户保留 5 条记录(行)并删除旧的。

谁能提供一个示例 Oracle 查询来执行上述场景。

提前致谢。

【问题讨论】:

    标签: sql oracle oracle11g


    【解决方案1】:
    delete from testp 
            where id in 
            (    select id
                 from
                 ( 
                      select id, row_number() over ( 
                              partition by name order by created_on desc ) rn
                      from testp)
                  where rn > 5
             )
    

    假设:

    1. 在本例中,表名为 testp。
    2. ID 是记录中的 PK。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      相关资源
      最近更新 更多