我有一个SQL头疼的时刻,并想知道是否有人可以提供帮助。使用此数据(例如):
workId rateRevision
1 1
1 2
1 3
2 1
3 1
3 2
4 1
4 2
4 3
...我基本上想要删除除最新版本(最高rateRevision值)之外的所有重复项。所以我最终得到:
workId rateRevision
1 3
2 1
3 2
4 3
理论上听起来很简单,但我无法在SQL中解决这个问题。这是我目前的代码:
SELECT * FROM rate r
WHERE r.rateRevision =
(select r.rateRevision from rate r ORDER BY r.rateRevision DESC LIMIT 1);
...但这只是返回
workId rateRevision
4 3
当然,这只是选择当前的值,但我计划基本上只是将其反转为delete语句。有人有什么想法吗?
非常感谢! 马特
答案 0 :(得分:2)
如下:
delete from rate r where r.rateRevision < (select max(r2.rateRevision) from rate r2 where r.workId = r2.workId)
答案 1 :(得分:1)
怎么样:
select workId, MAX(rateRevision) as MaxRevision
from MyTable
group by workId
结果:
workId MaxRevision
1 3
2 1
3 2
4 3
克里斯给了你最好的和最好的我想是最简单的答案。如果您想要删除重复项(例如保留最近的5个修订版,删除所有其余修订版),则可以使用CTE添加序数“行号”,如下所示。
WITH CTE AS
(
SELECT workId,
rateRevision,
ROW_NUMBER() OVER(PARTITION BY workId ORDER BY rateRevision DESC) AS Ordinal
FROM MyTable
)
DELETE FROM CTE
WHERE Ordinal > 5 -- You can keep the top "N" records (here we are just keeping the top 5)