首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么在一张表的同一行指定的几列数据中随机选出一个或数个数据

2012-09-29 
如何在一张表的同一行指定的几列数据中随机选出一个或数个数据假设目前有下表abcdefg1fdf3454a-dft4gh5_gd

如何在一张表的同一行指定的几列数据中随机选出一个或数个数据
假设目前有下表
  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

热点排行
Bad Request.