仅删除组的非最大记录

时间:2015-10-21 21:35:39

标签: sql max

我正在尝试执行以下操作

delete PreOrder
where preorderid not in (
select preorderid
from PreOrder p1
inner join (select max(OrderDt) OrderDt, preorderid
from preorder group by preorderid) p2 on
p1.preorderid=p2.preorderid
where p1.preorder in (1,2,3,4,5)

我只是尝试删除记录,如果只有那些。我得到了最大的工作,但是如何从那些具有该预编号的记录中删除

1 个答案:

答案 0 :(得分:1)

Delete p1
from PreOrder p1
left join (select max(OrderDt) OrderDt, preorderid
from preorder group by preorderid) p2 on
p1.preorderid=p2.preorderid
and p1.OrderDt = p2.OrderDt
where p2.preorderid is null and p1.preorderid in (1,2,3,4,5)