日期:2014-05-17 浏览次数:20530 次
--是要删除表中多余的数据,保留每个用户最新的两条的数据吗?如: delete UserLogin from UserLogin a where (select count(distinct logintime) from userlogin where userid=a.userid and logintime>=a.logintime)>2 --如果是查询最新的2条,不改变原始数据 select * from UserLogin a where (select count(distinct logintime) from userlogin where userid=a.userid and logintime>=a.logintime)<=2
------解决方案--------------------
对userid分组,使用row_number()over()排序 取<3就行。
------解决方案--------------------
建立插入触发器在触发器中引用一楼的删除语句:
delete UserLogin from UserLogin a
where a.userid=(select userid from inserted) and logintime not in (select top 2 logintime from userlogin where userid=(select userid from inserted) order by logintime)
------解决方案--------------------
此问题有点类似:http://www.dbfaq.net/FAQ/NewQL.aspx?QuestionID=71请参考
------解决方案--------------------
表记录的重复数据删除:
http://www.dbfaq.net/FAQ/FixupQL.aspx?QuestionID=30
------解决方案--------------------
; with cte ( select row_number() over( paritition by userid order by userid, logintime desc ) as xh ,* from UserLogin )
delete from cte where xh >=3
------解决方案--------------------