SQLite:具有条件和随机顺序的多选测试生成器

时间:2016-01-24 05:56:38

标签: sqlite

标题不是很清楚我希望在这里更好地描述我的问题 - 随意给我一个更好的标题。

我有一个查询,返回一个团队和分数表:

Team Scores
-------------
Team1    2
Team2    4
Team3    2
Team4    14
Team5    9
Team6    2
Team7    1
Team8    11
Team9    7

对于每个团队,我想创建三个额外的列,在Team1中选择不同的团队 - Team9,其得分低于团队考虑的分数。 为此目的,我们在这里将自己限制为分数> 2。 这可能是一个可能的结果:

Team Scores Res1   Res2   Res3
------------------------------
Team2    4  Team1  Team6  Team7
Team4    14 Team9  Team7  Team8
Team5    9  Team6  Team9  Team2
Team8    11 Team1  Team9  Team6
Team9    7  Team2  Team1  Team6

说这个表叫做T到目前为止我已经尝试了这个并不适用于另外一列:

Select T.score, T.team, 
    (Select tea as Res1 
        (Select T.team as tea, T.score as sco 
         from T where sco < T.score order by random()) limit 1)
from T;

1 个答案:

答案 0 :(得分:1)

使用三个单独的列执行此操作同时避免重复并不容易,因此最好使用一个由三行子查询中的group_concat()构造的单个列:

SELECT team,
       score,
       (SELECT group_concat(team)
        FROM (SELECT team
              FROM t AS t2
              WHERE t2.score < t.score
              ORDER BY random()
              LIMIT 3)
       ) AS res
FROM t
WHERE res LIKE '%,%,%';

(LIKE过滤掉没有其他三个团队的行。)