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

随机数问题
应用sql过程中,遇到如下问题,求实现功能的sql语句。
有一组数字(0,5,7,8,9,52,53,55,59,63,65,68,69,71,73,75,77,79,82,86,97,98,100,110,112,115,118,120,135,137,139,142,145,148,152,154,157,162,168,172,175,176,0,5,7,8,9,52,53,55,59,63,65,68,69,71,73,75,77,79,82,86,97,98,100,110,112,115,118,120,135,137,139,142,145,148,152,154,157,162,168,172,175,176)。
从这组数字中随机取2个数字,求的这2个数字的和;
从这组数字中(取2个数字后,剩余的数字中)再随机取2个数字,求的这2个数字的和;
比较这两个和的“个位数“(例和为105,个位数则为5)的大小,
如果前者个位数值大于后者个位数值,则把字符 "A "写入db1数据库的kk表的zifu列,
如果前者个位数值小于后者个位数值,则把字符 "B "写入db1数据库的kk表的zifu列,
如果前者个位数值等于后者个位数值,则把字符 "C "写入db1数据库的kk表的zifu列,

如此重复在这组数字中(前面取数字后剩余的数字中)随机取值,比较,写入数据库。
当这组数字中经过这样取值剩余的数字的个数在“4个-7个”时,停止取值。
求助!

------解决方案--------------------
declare @s varchar(8000)
set @s= '0,5,7,8,9,52,53,55,59,63,65,68,69,71,73,75,77,79,82,86,97,98,100,110,112,115,118,120,135,137,139,142,145,148,152,154,157,162,168,172,175,176,0,5,7,8,9,52,53,55,59,63,65,68,69,71,73,75,77,79,82,86,97,98,100,110,112,115,118,120,135,137,139,142,145,148,152,154,157,162,168,172,175,176 '

create table #t(id int,v int,f char(1))
set @s= 'insert #t(v) select * from (select '+replace(@s, ', ', 'as v union all select ')+ ' ) T order by newid() '
exec(@s)


declare @i int,@v1 int,@v2 int
set @i=0

update #t set id=(@i-1)/4,@i=@i+1,
@v1=case @i%4 when 1 then v
when 2 then @v1+v
else @v1 end,
@v2=case @i%4 when 3 then v
when 0 then @v2+v
else @v2 end,
f=(case when @i%4=0 and @v1> @v2 then 'A '
when @i%4=0 and @v1 <@v2 then 'B '
when @i%4=0 and @v1=@v2 then 'C '
else ' ' end
)

--下面是把剩余数ID改为NULL
update #t set id=null,f= ' ' where id in (select id from #t group by id having(count(*) <4))

update A set id=null,f= ' ' from #t A where not exists(select 1 from #t where f is not null and id <A.id)

select * from #t order by id

drop table #t


--结果:

id v f
----------- ----------- ----
NULL 157
NULL 75
NULL 8
NULL 112
1 55
1 68
1 73
1 135 B
2 59
2 53
2 71
2 152 B
3 168
3 65
3 175
3 110 B
4 162
4 5
4 82
4 79 A
5 71
5 100
5 7
5 52 A
6 118
6 86
6 5
6 145 A
7 162
7 52
7 172
7 118 B
8 69
8 69
8 110
8 152 B
9 148
9 75
9 154
9 68 A
10 82
10 120
10 65
10 115 A
11 100
11 9
11 59
11 137 B
12 8