SQL中关于随机数问题

zhouxinjie 2003-12-29 12:05:25
数据表中记录如下:

学号 姓名 年级 班级
1 周伟 2001 3
2 刘伟 2001 3
3 夏可 2001 3
4 小雄 2001 1
5 周涛 2002 3
6 朱伟 2002 3
7 刘江 2001 1
8 王海 2001 3
我想在年级为2001,班级为3的所有记录中随机选取3条记录,而且这三个不能重复。请问,各位这个怎么实现?这个SQL语句怎么写?
...全文
106 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
胖河马 2003-12-30
  • 打赏
  • 举报
回复
newid是SQLServer的函数,返回一个GUID,Access中没有
zhouxinjie 2003-12-29
  • 打赏
  • 举报
回复
请问,哪个newid()是个什么东东啊?是函数吗?还是要怎么办?谢谢各位再次指导一下!
wzh1215 2003-12-29
  • 打赏
  • 举报
回复
select * from 表 where 学号 in(select top 3 学号 from 表 where 年级='2001' and 班级=3 order by newid())
zjcxc 2003-12-29
  • 打赏
  • 举报
回复
select * from 表 where 学号 in(select top3 from 表 where 年级='2001' and 班级=3 order by newid())
zhouxinjie 2003-12-29
  • 打赏
  • 举报
回复
不好意思,这个newid()好像是SQL中才有的吧,我在ACCESS中测试的时候,提示它未定义。

现在知道啦,应该是sql中自带的函数吧!不知道我说的是不是?请再次回答我,好吗?我马上结贴!谢谢各位啦!
Jianli2004 2003-12-29
  • 打赏
  • 举报
回复
create table #stu(xh int,xm char(6),grade char(6),class int)
insert into #stu values(1 , '周伟', '2001', 3)
insert into #stu values(2 , '刘伟', '2001', 3)
insert into #stu values(3 , '夏可', '2001', 3)
insert into #stu values(4 , '小雄', '2002', 1)
insert into #stu values(5 , '周涛', '2002', 3)
insert into #stu values(6 , '朱伟', '2001', 3)
insert into #stu values(7 , '刘江', '2001', 1)
insert into #stu values(8 , '王海', '2001', 3)

declare @max_xh int,@min_xh int,@xh1 int,@i int
declare @x table(myxh int)

set @i=3

select @max_xh=max(xh),@min_xh=min(xh) from #stu where grade='2001' and class=3

while @i>=1
BEGIN
loop1:
SELECT @xh1=right(left(RAND( (DATEPART(mm, GETDATE()) * 10000000 )
+ (DATEPART(ss, GETDATE()) * 1000 )
+ DATEPART(ms, GETDATE()) ),5),2)

while @xh1>@max_xh
set @xh1=@xh1-@max_xh

IF exists (select myxh from @x where myxh=@xh1) or @xh1<@min_xh or
@xh1 not in (select xh from #stu where grade='2001' and class=3 )
goto loop1
else
insert into @x values(@xh1)
set @i=@i-1
END

select * from @x
select * from #stu where xh in (select myxh from @x) and grade='2001' and class=3

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧