从正确答案列表中生成错误答案

时间:2017-12-28 19:36:15

标签: sql sqlite

我想从包含具有正确答案的问题的表中编写查询。我想要3个更多的列,这些是从正确的答案列生成的错误答案我写了一个查询,但我认为它不能完美地工作。

 SELECT q1.Question, q1.Correct , q2.Correct Wrong1, q3.Correct Wrong2, q4.Correct Wrong3
From Questions q1 
LEFT JOIN 
(SELECT correct FROM Questions ORDER by RANDOM() LIMIT 1) q2
LEFT JOIN 
(SELECT correct FROM Questions ORDER by RANDOM() LIMIT 1) q3
LEFT JOIN 
(SELECT correct FROM Questions ORDER by RANDOM() LIMIT 1) q4
ON q1.correct != q2.correct AND
q1.correct != q3.correct AND 
q2.correct != q3.correct AND 
q1.correct != q4.correct AND 
q2.correct != q4.correct AND 
q3.correct != q4.correct

1 个答案:

答案 0 :(得分:0)

我花了一些时间来创建一个使用CROSS APPLYPIVOT的完美优雅的解决方案,然后看到dbms是SQLite,而不是SQL Server。也许其他人可以把它转换成SQLite:

SELECT Question
    , Correct
    , Wrong1 = piv.[3]
    , Wrong2 = piv.[2]
    , Wrong3 = piv.[1]  
FROM 
(
    SELECT Question = q1.Question
        ,Correct = q1.Correct 
        ,ca1.Wrong 
        ,RowNum = ROW_NUMBER() OVER (PARTITION BY q1.Question ORDER BY q1.Question)
    FROM Questions q1
    CROSS APPLY (SELECT TOP 3 Wrong = q2.Correct FROM Questions q2 WHERE q2.Correct <> q1.Correct ORDER BY NEWID()) ca1
) src
PIVOT
(
  MIN(Wrong)
  FOR RowNum IN ([1], [2], [3])
) piv;