【问题标题】:Oracle Dense RankOracle Dense_rank
【发布时间】:2018-01-10 06:30:42
【问题描述】:

我需要根据 ID 和时间列删除重复的行。我只需要保留最新时间的记录。如果有两条记录的时间最长,我可以保留任何一条记录并删除其中的所有其他记录该组。请在下面找到我的输入数据

ID  TIMES
123 13/01/2018
123 14/01/2018
123 15/01/2018
345 14/01/2018
567 20/01/2018
567 20/01/2018
879 NULL
879 21/01/2018

我已经写了一个查询,但它不适用于 ID=567 的情况,因为它们在时间列中具有相同的值。请在下面找到我的查询

delete FROM table where (ID,times) in( 
  SELECT ID,times, 
    RANK() OVER (PARTITION BY ID ORDER BY times DESC NULLS LAST) dest_rank
    FROM TABLE 
  ) WHERE dest_rank <> 1

有什么办法可以做到这一点。

【问题讨论】:

  • 您可以轻松修复您的解决方案 - 这并不比接受的答案更糟。问题是您使用了RANK() 函数。您应该改用ROW_NUMBER() 函数。正如您所发现的,RANK() 函数将显示具有相同排名的关系,所以这对您没有帮助。在平局的情况下,ROW_NUMBER() 将任意为行分配不同的数字,这就是您所需要的。

标签: sql oracle dml


【解决方案1】:

这是一种方法:

delete t from t
    where rowid <> (select max(rowid) keep (dense_rank first order by times desc)
                    from t t2
                    where t2.id = t.id
                   );

但是,我会使用临时表来执行此操作:

create temporary table tt
    select id, max(times) as times
    from t
    group by id;

truncate table t;

insert into t(id, times)
    select id, times
    from tt;

【讨论】:

  • 我认为我们需要使用rowid,而不是rowid=
  • @GIN 。 . .很好的收获。
【解决方案2】:

您可能会通过贡献或rowid 获得成功:

delete mytable where (rowid) in
(
  select t1.rowid from mytable t1
   where times <
  (
  select max(times)
    from mytable t2
   where t2.id = t1.id  
     and t2.times != t1.times -- for non-matching records of times
  )
  union all
  select t1.rowid from mytable t1
   where rowid <
  (
  select max(rowid)
    from mytable t2
   where t2.id = t1.id
     and t2.times = t1.times  -- for matching records of times
  )
);

【讨论】:

    【解决方案3】:

    我会的

    delete demo where rowid in
    ( select lag(rowid) over (partition by id order by times nulls first) from demo  );
    

    您没有说您希望如何处理 null 值。如果要保留日期为空的行,请将 nulls first 更改为 nulls last。

    【讨论】:

      猜你喜欢
      • 2021-01-10
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 2012-06-01
      • 2012-06-26
      • 1970-01-01
      相关资源
      最近更新 更多