日期:2014-05-18 浏览次数:20478 次
use test go declare @t table([id] int NOT NULL,pname varchar(10) NULL,num int NULL) insert into @t select 1, 'a ',11 union all select 2, 'a ',23 union all select 3, 'b ',34 union all select 4, 'b ',45 union all select 5, 'c ',56 union all select 6, 'b ',78 union all select 7, 'd ',99 union all select 8, 'd ',100 declare @tmp table([id] int NOT NULL,pname varchar(10) NULL,num int NULL) while 200>(select isnull(sum(num),0) from @tmp) insert @tmp select top 1 * from @t where id not in(select id from @tmp )order by NewID() select pname,[比率]=rtrim(cast(sum(num)*1.0/(select sum(num) from @tmp)*100 as decimal(18,2)))+'%' from @tmp group by pname select * from @tmp ----------- pname 比率 ---------- ----------------------------------------- a 9.39% b 50.20% d 40.41% (所影响的行数为 3 行) id pname num ----------- ---------- ----------- 6 b 78 4 b 45 2 a 23 7 d 99 (所影响的行数为 4 行)
------解决方案--------------------
SQL SERVER2005里有一个新的关键词叫做TABLESAMPLE, 就是用来做抽样统计的, 不过好象只能取百分比,譬如1%, 不能取某个数。
不过我想你可以先确定整个表有多少个数据, 然后大概估计出多少个百分比是200条。然后多取一个百分比, 再取前200条就可以了。
至少LZ说的销售记录不全的问题,LZ应该能很轻松解决吧?
select top 200 * from ( select pname, num, num/sum(num) as [percent] from #table Tablesample(2) )T