7

假设一个表结构:

Create Table Question
{
ID int pk,
Category varchar
Stem varchar,
AnswerA varchar,
...
AnswerD varchar,
Correct char,
isMandatory bit

}

对于给定的类别,大约有 50 个问题。可以有 1-10 个必填问题。

我需要选择所有强制性问题,然后随机选择足够多的其他问题来制作一个包含 20 个问题的问题集。

4

3 回答 3

7

好的,这个怎么样

select top 20 * from question
where category = @category
order by isMandatory desc, newid()

请参阅接受的答案以了解数据库表中的 newid()随机记录 (T-SQL)背后的原因

于 2012-06-03T19:12:23.557 回答
6
;WITH T 
     AS (SELECT *, 
                ROW_NUMBER() 
                  OVER (PARTITION BY Category 
                            ORDER BY isMandatory DESC, CRYPT_GEN_RANDOM(4)) RN 
         FROM   Question) 
SELECT * 
FROM   T 
WHERE  RN < = 20 
于 2012-06-03T19:12:27.227 回答
0
   Declare @number_of_nonmandat INT

   Select @number_of_nonmandat=count(1)
   FROM Question
   where isMandatory =1

   SET @number_of_nonmandat=20-number_of_nonmandat;

    IF(@number_of_nonmandat>0)
    BEGIN
         Select *
         FROM Question
         where isMandatory =1
           UNION 
         SELECT TOP (@number_of_nonmandat)  *
         FROM Question
         where isMandatory<>1
         ORDER BY newID()
    END
    ELSE 
    BEGIN
        Select top 20 *
         FROM Question
         where isMandatory =1

    END
于 2012-06-03T19:07:14.333 回答