删除特定 ID 的最旧行 - Sybase 派生表问题



我的存储过程有一个临时表,其中包含一列 ID 值。 一个 ID 可以多次出现在临时表中。 临时表中还有一个日期列。 我需要编写一个查询(Sybase 数据库),该查询将删除所有不是每个 ID 的最大日期的条目。

ID    |  Date
12345 |  2015/01/23
98763 |  2015/01/22
12345 |  2015/01/20
98763 |  2015/01/21

所以在这种情况下

12345 | 2015/01/20 and 98763 | 2015/01/21 

条目将被删除。

我创建了以下内容:

DELETE #temp
FROM #temp t1
left JOIN 
(
   select ID, MAX(Date) maxdt
   from #temp t2
   group by ID
) t2 on t1.ID = t2.ID
  and t1.ID = t2.Date
where t2.ID is null

尽管事实证明Sybase(或至少是我正在使用的版本)不允许在删除或更新状态中派生表。 是否有另一种可以重写的方法,或者使用不同的查询方法来获取此功能?

下面的代码只留下最新的行:

delete #temp   
from #temp t       
where not exists(select 1
                 from #temp t2 
                 where t.id = t2.id
                 and t2.date < t.date)

最新更新