日期:2014-05-18  浏览次数:20498 次

求教一个问题,SQL循环执行
问题:我有一个表,其中一个是日期字段,

date 字段
2011-01-01   xxx
2011-01-01 xxx
2011-01-01 
2011-01-02
2011-01-02
....
.....
2011-11-07

我现在想按日期进行删除 ,只删除一天当中记录数的固定百分比,从2011-01-01 一直执行到2011-11-07,每天的记录数是不固定的,怎么写,谢谢

在线等

------解决方案--------------------
SQL code
delete from tb where id in( --id列为唯一性列
select id from( 
select id,row_number()over(partition by date order by newid())rn,(select count(*) from tb where date=a.date)ct from tb a
)t where rn*100/ct<=80  --删除80%

------解决方案--------------------
SQL code
这方法比较好用的方法NTILE()--按百分比删除

--> --> (Roy)生成測試數據
 
if not object_id('Tempdb..#T') is null
    drop table #T
Go
Create table #T([date] Datetime)
Insert #T
select '2011-01-01' union all
select '2011-01-01' union all
select '2011-01-01' union all
select '2011-01-01' union all
select '2011-01-01' union all
select '2011-01-01' union all
select '2011-01-01' union all
select '2011-01-01' union all
select '2011-01-01' union all
select '2011-01-01' union all
select '2011-01-02' union all
select '2011-01-02'
Go
delete t
from 
(Select *,NTILE(10)over(partition by [date] order by [date]) as row from #T)t
where row<=8---删除80%

select * from #T

------解决方案--------------------
赞成,很少用的一个函数
终于派上用场了
LZ注意2005+才能用
探讨

SQL code
这方法比较好用的方法NTILE()--按百分比删除

--> --> (Roy)生成測試數據

if not object_id('Tempdb..#T') is null
drop table #T
Go
Create table #T([date] Datetime)
Insert #T
select '2011-01-01' union all
select ……