今天去笔试:遇到一个题目,题目大概是这样的:
有一个试题表:T_EXAM {ID,type(1,2,3/表示试题类型),difficulty(1,2/试题难度),distinguish(1,2/区分)}
现在我要从题库随机抽出20道题,type:类型1的6道,2的7道,3的7道;difficulty:难度1的8道,2的12道;distinguish:区分1的13道,2的7道:请问能用SQL查询出来吗?
如果能用SQL查询出来,SQL语句该怎么写?
------解决方案--------------------
简单的写应该是这样的,期待更牛逼的算法。
select top 6 * from tb where type=1 and difficulty=1 and distinguish=1 oder by newid()
union all
select top 2 * from tb where type=2 and difficulty=1 and distinguish=1 oder by newid()
union all
select top 5 * from tb where type=2 and difficulty=2 and distinguish=1 oder by newid()
union all
select top 7 * from tb where type=2 and difficulty=2 and distinguish=2 oder by newid()
------解决方案--------------------
if object_id('T_EXAM') is not null
begin
drop table [T_EXAM]
end
CREATE TABLE [dbo].[T_EXAM](
[ID] [int],
[type] [int] NULL,
[difficulty] [int] NULL,
[distinguish] [int] NULL
) ON [PRIMARY]
insert into [T_EXAM]([ID],[type],[difficulty],[distinguish])
select top 10000 row_number()over(order by newid()), abs(checksum(newid())%3)+1,abs(checksum(newid())%2)+1,abs(checksum(newid())%2)+1 from master.dbo.spt_values a
declare @match int
declare @count1 int
declare @count2 int
set @match=0
while (@match<>1)
begin
if object_id('tempdb..#temp') is not null
drop table #temp
select top 6 * into #temp from T_EXAM
where type=1
order by newid()
insert into #temp
select top 7 * from T_EXAM
where type=2
order by newid()
insert into #temp
select top 7 * from T_EXAM
where type=3
order by newid()
/*8*/
select @count1=count(*) from #temp
where [difficulty]=1
/*13*/
select @count2=count(*) from #temp
where [distinguish]=1
print @count1
print @count2
if (@count1=8 and @count2=13)
begin
set @match=1
break
end
end
select * from #temp
------解决方案--------------------
create table #tb(
id int ,
[type] int,
[difficurity] int,
[distinguish] int);
insert into #tb select top 1 * from T_EXAM order by NEWID()
declare @count int=1
while @count<20
begin
begin tran
insert into #tb select top 1 * From T_EXAM
order by NEWID()
if 6 <(select COUNT(*) from #tb where [TYPE]=1)