3

我有 2 张桌子:Persons(idPerson INT)Questions(idQuestion INT).

我想将数据插入到第三个表中:OrderedQuestions(idPerson INT, idQuestion INT, questionRank INT)

我想以随机顺序将所有问题分配给所有人。

我想过做一个 CROSS JOIN 但后来,我得到了每个人的相同顺序的问题。

INSERT INTO OrderedQuestions
    SELECT idPerson, idQuestion, questionRank FROM Persons 
    CROSS JOIN
    (SELECT idQuestion,ROW_NUMBER() OVER (ORDER BY NEWID()) as questionRank
    FROM Questions) as t

我怎样才能为每个人实现这样一个随机的、不同的排序?

显然,我希望解决方案尽可能快。(可以使用 TSQL 或 Linq to SQL 来完成)


3 个人和 5 个问题的预期结果:

   idPerson         idQuestion         questionRank
1.  1                18                  1
2.  1                14                  2
3.  1                25                  3
4.  1                31                  4
5.  1                2                   5
6.  2                2                   1
7.  2                25                  2
8.  2                31                  3
9.  2                18                  4
10. 2                14                  5
11. 3                31                  1
12. 3                18                  2
13. 3                14                  3
14. 3                25                  4
15. 3                2                   5

我刚刚编辑了结果(由于 ID 是自动生成的,它们不能用于对问题进行排序)。

4

1 回答 1

2

这可能会写得更有效,但它满足所有要求。

SELECT 
    idperson, 
    idQuestion,
    ROW_NUMBER() OVER (PARTITION BY personid ORDER BY ordering) as questionRank 
FROM (
    SELECT idperson, idQuestion, ordering 
    FROM person
    CROSS JOIN 
    (
        SELECT idQuestion, NewID() as ordering FROM Question
    ) as t
) as a
order by personid, QuestionRank
于 2012-09-20T20:58:42.477 回答