SQL Server:转换子选择查询以加入

时间:2012-05-11 19:06:14

标签: sql sql-server sql-server-2005

我有两个表questionpoolquestion,其中questionquestion pool的多对一表。我使用子选择查询创建了一个查询,该查询返回正确的随机结果,但我需要从question表返回多个列。

查询的目的是从'问题'表中为'问题池'表中的每个'QuizID'返回一个随机测试。

SELECT QuestionPool.QuestionPoolID,
(
SELECT TOP (1) Question.QuestionPoolID
FROM Question
WHERE Question.GroupID = QuestionPool.QuestionPoolID
ORDER BY NEWID()
)
FROM QuestionPool
WHERE QuestionPool.QuizID = '5'

4 个答案:

答案 0 :(得分:3)

OUTER APPLY适用于此:

Select *
FROM QuestionPool
OUTER APPLY
(
    SELECT TOP 1 * 
    FROM Question
    WHERE Question.GroupID = QuestionPool.QuestionPoolID
    ORDER BY NEWID()
) x
WHERE QuestionPool.QuizID = '5'

OUTER APPLY的另一个例子是使用http://www.ienablemuch.com/2012/04/outer-apply-walkthrough.html


实时测试:http://www.sqlfiddle.com/#!3/d8afc/1

create table m(i int, o varchar(10));
insert into m values
(1,'alpha'),(2,'beta'),(3,'delta');

create table x(i int, j varchar, k varchar(10));

insert into x values
(1,'a','hello'),
(1,'b','howdy'),
(2,'x','great'),
(2,'y','super'),
(3,'i','uber'),
(3,'j','neat'),
(3,'a','nice');


select m.*, '' as sep, r.*
from m
outer apply
(
  select top 1 *
  from x
  where i = m.i
  order by newid()
) r

答案 1 :(得分:0)

不熟悉SQL服务器,但我希望这样做:

Select QuestionPool.QuestionPoolID, v.QuestionPoolID, v.xxx -- etc
FROM   QuestionPool
JOIN
       (
        SELECT   TOP (1) *
        FROM     Question
        WHERE    Question.GroupID = QuestionPool.QuestionPoolID
        ORDER BY NEWID()
       ) AS v ON v.QuestionPoolID = QuestionPool.QuestionPoolID
WHERE  QuestionPool.QuizID = '5'

答案 2 :(得分:0)

您的查询似乎为每个QuestionPool.QuestionPoolId带回了QuizId过滤器的任意Question.QuestionPoolId。

我认为以下查询是这样做的:

select qp.QuestionPoolId, max(q.QuestionPoolId) as any_QuestionPoolId
from Question q join
     qp.QuestionPoolId qp
     on q.GroupId = qp.QuestionPoolId
 WHERE QuestionPool.QuizID = '5' 
group by qp.QuestionPoolId

这会返回一个特定的问题。

以下查询将允许您获取更多字段:

select qp.QuestionPoolId, q.*
from (select q.*, row_number() over (partition by GroupId order by (select NULL)) as randrownum
      from Question q
     ) join
     (select qp.QuestionPoolId, max(QuetionPool qp
     on q.GroupId = qp.QuestionPoolId
 WHERE QuestionPool.QuizID = '5' and
       randrownum = 1

这使用row_number()来任意枚举行。 “选择NULL”提供随机排序(或者,您可以使用“按GroupId排序”。

答案 3 :(得分:0)

通用表格表达式(CTE)对于这类事物来说非常方便......

http://msdn.microsoft.com/en-us/library/ms175972(v=sql.90).aspx