我想删除最近30天之外,每天的一部分数据,只保留指定时间的数据。假如:每天会新增10条数据,并记录日期和时间。每隔30天会执行一个存储过程,将每天的10条数据删除其中8条,保留2条,这2条数据是我指定的时间,比如保留早晨9点和下午6点两个时间点的数据,如果某一天只新增了2条或2条以下的数据,则不删除。前提条件是,只删除30天之前的数据,最近30天的数据全部保留。
调试欢乐多
select * from InspectRecord
where (datepart(hh,IR_Time) <> 9 and datepart(hh,IR_Time) <> 6) and
IR_Time < dateadd(mm,-1,getdate())时间段和制定时间都有了,但不知道怎么判断一天超过2条记录。请教!
拆解问题:
1、datediff(d,date,getdate())>30
2、获取每天的数据行数
3、获取固定时间的数据行数
4、判断3步骤的结果 True 返回此时间数据,剩余数据删除
False 获取当天数据的top 2,剩余数据删除
--加上条件
and substring(convert(varchar(20),IR_time,120),1,10) in
(select substring(convert(varchar(20),IR_time,120),1,10) newtime
from InspectRecord
group by substring(convert(varchar(20),IR_time,120),1,10)
having count(substring(convert(varchar(20),IR_time,120),1,10))>2)
每天数据的时间列IR_time前面的都是一样的,所以用substring(convert(varchar(20),IR_time,120),1,10) as newtime来截取,实际上可以直接用convert(varchar(10),IR_time,120),只是为了方便理解。
这样就有很多相同的newtime,再用group by 分组,having count(newtime)>2来筛选。