0

我有这张表QUESTIONS,其中包含 500 条记录,其中包含以下列:

Q_ID
Q_difficulty('easy','medium','hard')
Q_subject('MATH','SCIENCE','LANGUAGE','HISTORY')
Question(the actual question)

我需要获得 100 条随机记录,包括 20 条简单、60 条中等和 20 条困难,但我必须考虑获得每个主题的 25%。

我知道如何通过以下方式变得容易、中等和困难:

go
select top 20 from QUESTIONS where Q_difficulty='easy' order by NEWID()
go
select top 60 from QUESTIONS where Q_difficulty='medium' order by NEWID()
go
select top 20 from QUESTIONS where Q_difficulty='hard' order by NEWID()

我的问题是如何使查询具有每个主题的 25%。顺便说一句,我正在使用 SQL 服务器 :(

4

2 回答 2

1
SELECT
   X.*
FROM
   (VALUES
      ('easy', 5), ('medium', 15), ('hard', 5)
   ) D (Difficulty, Qty)
   CROSS JOIN (VALUES
      ('MATH'), ('SCIENCE'), ('LANGUAGE'), ('HISTORY')
   ) S (Subject)
   CROSS APPLY (
      SELECT TOP (D.Qty)
         Q.*
      FROM
         dbo.Questions Q
      WHERE
         D.Difficulty = Q.Difficulty
         AND D.Subject = Q.Subject
      ORDER BY
         NewID()
   ) X
于 2013-07-25T09:35:37.760 回答
0

您必须将其分解为各个百分比:

select top 5 * INTO #tmp from QUESTIONS where Q_difficulty='easy' AND Q_subject='MATH' order by NEWID();
INSERT INTO #tmp
select top 5 * from QUESTIONS where Q_difficulty='easy' AND Q_subject='SCIENCE' order by NEWID();
INSERT INTO #tmp
select top 5 from QUESTIONS where Q_difficulty='easy' AND Q_subject='LANGUAGE' order by NEWID();
INSERT INTO #tmp
select top 5 from QUESTIONS where Q_difficulty='easy' AND Q_subject='HISTORY' order by NEWID();
INSERT INTO #tmp
select top 15 from QUESTIONS where Q_difficulty='medium' AND Q_subject='MATH' order by NEWID();
INSERT INTO #tmp
select top 15 from QUESTIONS where Q_difficulty='medium' AND Q_subject='SCIENCE' order by NEWID();
INSERT INTO #tmp
select top 15 from QUESTIONS where Q_difficulty='medium' AND Q_subject='LANGUAGE' order by NEWID();
INSERT INTO #tmp
select top 15 from QUESTIONS where Q_difficulty='medium' AND Q_subject='HISTORY' order by NEWID();
INSERT INTO #tmp
select top 5 from QUESTIONS where Q_difficulty='hard' AND Q_subject='MATH' order by NEWID();
INSERT INTO #tmp
select top 5 from QUESTIONS where Q_difficulty='hard' AND Q_subject='SCIENCE' order by NEWID();
INSERT INTO #tmp
select top 5 from QUESTIONS where Q_difficulty='hard' AND Q_subject='LANGUAGE' order by NEWID();
INSERT INTO #tmp
select top 5 from QUESTIONS where Q_difficulty='hard' AND Q_subject='HISTORY' order by NEWID();
SELECT * FROM #tmp
于 2013-07-25T06:54:05.603 回答