日期:2014-05-17  浏览次数:20862 次

问一个存储过程中按比例附值的问题
查询语句,查出一组ID,每天运行一次,每天的结果数都不一样。
我怎么在存储过程中,按固定的比例给这些查出的ID后面附值。

比如 2012-11-20 查出5000个ID
 1/5 的ID值附 100
 1/5 的ID值附 50
 1/5 的ID值附 80
 1/5 的ID值附 10
 1/5 的ID值附 30
  
     2012-11-21 查出7001个ID
 1/5 的ID值附 100
 1/5 的ID值附 50
 1/5 的ID值附 80
 1/5 的ID值附 10
 1/5 的ID值附 30
------解决方案--------------------
思路:预先查出每天所查的id总数(可将查出的id放到一个临时表temp中,要设置的表为test),存储过程里面设置五个参数作为输入,前五分之一为第一个参数id的值,第二个五分之一为第二个参数id的值......(存储过程也可以设置六个参数,其中一个作为id总数),后面一种方法应该好一些,我是学生,可能有错误,你懂的
代码:sql server中实现:[code=sql]select * into @count from temp
create procedure pro_name
@count int,@a1 int,@a2 int,@a3 int,@a4 int,@a5 int
as 
declare @c int--c为五分之一的id总数值
begin
select @c=1
while(@c<@count/5)
insert into test.id values(@a1)
set @c=@c+1
end
begin
select @c=1
while(@c<@count/5)
insert into test.id values(@a2)
set @c=@c+1
end
begin
select @c=1
while(@c<@count/5)
insert into test.id values(@a3)
set @c=@c+1
endbegin
select @c=1
while(@c<@count/5)
insert into test.id values(@a4)
set @c=@c+1
end
begin
select @c=1
while(@c<@count/5)
insert into test.id values(@a5)
set @c=@c+1
end
------解决方案--------------------
--用分析函数ntile+case语句即可,例如
select emp.*, 
case ntile(5) over (order by rownum)
  when 1 then 100
  when 2 then 50
  when 3 then 80
  when 4 then 10
  else 30
end
from emp;