SQL选择随机记录来完成类别

时间:2013-07-25 06:17:33

标签: sql-server-2008

我有这张表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服务器:(

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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