34,576
社区成员
发帖
与我相关
我的任务
分享
delete a
from temp a where not exists(select * from (select top 5 * from temp where userid=a.userid order by operatedate desc) b where operatedate=a.operatedate)
--先查询出来看看结果是否正确
select * from t1 where UserID in (
select UserID from t1 group by UserID
having exists (select UserID from t1 group by UserID having count(1)>5)
and OperateDate=min(OperateDate) )
--然后进行删除操作
delete from t1 group by UserID
having exists (select UserID from t1 group by UserID having count(1)>5)
and OperateDate=min(OperateDate)
delete from temp a where
userid in(
select userID from temp group by userid having count(userid)>5
) and operatedate not in(
select top 5 operatedate from temp where userid=a.userid order by operatedate desc
)
--> --> (Ben)生成測試數據
if not object_id('tb') is null
drop table tb
Go
Create table tb(UserID varchar(10), OperateDate datetime)
Insert tb
select N'aaa','2008-04-02 14:58:13.073' union all
select N'aaa','2008-04-02 19:28:17.307' union all
select N'aaa','2008-04-02 19:28:43.870' union all
select N'aaa','2008-04-03 12:45:54.353' union all
select N'aaa','2008-04-03 12:46:35.557' union all
select N'aaa','2008-04-04 00:56:23.290' union all
select N'aaa','2008-04-06 00:10:04.887' union all
select N'aaa','2008-04-06 04:25:31.997'
Go
Select * from tb order by operatedate
delete from tb
where userid in (select userid from tb group by userid having count(*)>5)
and operatedate in(select top 3 operatedate from tb where userid in (select userid from tb group by userid having count(*)>5) order by operatedate)
select * from tb
结果:
aaa 2008-04-03 12:45:54.353
aaa 2008-04-03 12:46:35.557
aaa 2008-04-04 00:56:23.290
aaa 2008-04-06 00:10:04.887
aaa 2008-04-06 04:25:31.997