请教一个关于SQL随机查询问题

来源:百度知道 编辑:UC知道 时间:2024/05/09 09:06:41
请教诸位大侠,现在假设有这样一个表,表名为“成绩”,表内容如下:
姓名 成绩
a 85
b 90
c 70
d 95
e 60
f 83
g 100
h 65
i 73
..........
现在需要随机抽取四条记录,并且其成绩和小于330分。
并且每次抽取的记录不能一样。
语句越简单越好,解释越详细越好。
小弟在此先谢过了。
随机抽取四条记录我自己会写的:select top 4 * from 成绩
order by newid()
但问题是怎么限定这四条记录的成绩和小于330。
谢谢。。。。。。

--创建表
create table r
(
id int identity(1,1) primary key,
name varchar(20),
cj int
)
--插入记录
insert into r values('a',90)
insert into r values('b',80)
insert into r values('c',70)
insert into r values('d',60)
insert into r values('e',65)
insert into r values('f',50)
insert into r values('g',45)
insert into r values('h',40)
insert into r values('i',35)
--查看下
select * from r
--sql语句处理,可写成存贮过程
create proc myrandom
as
begin
--存储过程具体实现
declare @a int
set @a=1
while 1=1
begin
select top 4 * into x from r order by newId()
select @a=count(*) from (select * from x where (select sum(cj) from x)<280) as a
if @a<>0
begin
select * from x
break
end
drop table x
end
drop table x
end

单条语句:
select * from (select top 4 *