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

如何得到前想要的SN
谢谢各位了,本人水平太有限了,不好意思!
table 
sn sl aa
1 5 null
2 8 null
3 10 null
4 25 null
5 30 null
要求通过SQL语名得到sl占sl总和比80%的sn号


------解决方案--------------------
SQL code
 
create table #tab(sn int identity,sl int,aa varchar(10))

insert into #tab(sl) select 5 union all select 8 union all select 10 union all select 25 union all select 30


select a.*,convert(float,a.sl)*100/b.sum_sl 'sl%' from #tab a,(select sum_sl=sum(sl) from #tab) b
where (select sum(sl) from (select a.sn,convert(float,a.sl)*100/b.sum_sl sl from #tab a,(select sum_sl=sum(sl) from #tab) b) c where c.sn <=a.sn) <=80

--结果
sn      sl      aa    sl%                         
----------- ----------- ---------- -----------------------------------------------------
1      5      NULL    6.4102564102564106
2      8      NULL    10.256410256410257
3      10      NULL    12.820512820512821
4      25      NULL    32.051282051282051

(所影响的行数为 4 行)