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

如何在一张表的同一行指定的几列数据中随机选出一个或数个数据
假设目前有下表
  a b c d e f g
  1 fd f34 54a- dft4 gh5_g dfttg
  2 tewrt t5e ret4 hrt gh+ dfs3
  3 dtr fsd erw3 fs +_dsf sdg
  4 sdf3 54f 43 ghr 546d fsgh
……
如上,假设a,b,c,d,e,f,g为列名,
现在如果我要在a=2的那一行数据中的b,e,g这三列中随机选取1个数据,用sql语言应该怎么写?
随机选取多个数据呢?

------解决方案--------------------
SQL code

select case when rand() between 0 and 0.3 then b
        when rand() between 0.3 and 0.6 then e
        else g end 
from 你的表
where a=2;

------解决方案--------------------
这个是取随机column
create table #a(a int , b varchar(10),c varchar(10),d varchar(10),e varchar(10),f varchar(10),g varchar(10))

insert into #a
 select 1 ,'fd' ,'f34' ,'54a-' ,'dft4' ,'gh5_g' ,'dfttg' union all
 select 2, 'tewrt', 't5e', 'ret4', 'hrt' ,'gh+', 'dfs3' union all
 select 3, 'dtr', 'fsd', 'erw3', 'fs' ,'+_dsf' ,'sdg'

--select * from #a

declare @t int 
select @t=cast(RAND()*3 as int)
select (case @t when 0 then b when 1 then e when 2 then g end )x from #a where a=2