选择SUM然后将其用作SELECT TOP的参数

时间:2013-10-30 07:49:17

标签: tsql sql-server-2005

我想在一个SQL命令中使用这两个SQL语句。帮助:)

声明#1:

SELECT SUM(nrofitems) as totItems 
FROM tblSets 
WHERE moduleexamID = 20

声明#2:

SELECT TOP (cast(totItems as int)) questions
FROM tblQuestions 
WHERE moduleexamID = 20 
ORDER BY NEWID()

3 个答案:

答案 0 :(得分:0)

只需使用ROW_NUMBER()

这样的事情:

SELECT * FROM
(
SELECT tblQuestions.*,
       ROW_NUMBER() OVER (ORDER BY NEWID()) as RN
FROM tblQuestions 
WHERE moduleexamID = 20 
) as T1
WHERE RN<=
        ISNULL(
        (SELECT SUM(nrofitems) as totItems 
                FROM tblSets 
                WHERE moduleexamID = 20
        ),0);

答案 1 :(得分:0)

您也可以尝试关注:

;WITH a AS (
    SELECT moduleexamID, SUM(nrofitems) as totItems 
    FROM tblSets 
    GROUP BY moduleexamID
)
SELECT b.questions
FROM a
    CROSS APPLY (
        SELECT TOP (cast(a.totItems as int)) questions
        FROM tblQuestions 
        WHERE moduleexamID = a.moduleexamID
        ORDER BY CHECKSUM(NEWID())
    ) b
WHERE a.moduleexamID = 20

答案 2 :(得分:0)

create table #tblSets (
    moduleexamID int,
    moduleId int,
    nrofitems int
)
go
create table #tblQuestions (
    moduleexamID int,
    body varchar(1024)
)
go
insert into #tblQuestions values
    (20,'aaaaaa'),
    (20,'bbbbbb'),
    (20,'cccccc'),
    (20,'dddddd'),
    (21,'eeeeee'),
    (21,'ffffff'),
    (20,'gggggg')
go
insert into #tblSets values
    (20,1,1),
    (20,2,2),
    (21,1,1),
    (22,1,3)
go
select top (
    select sum(s.nrofitems)
    from #tblSets s
    where s.moduleexamID=20
) *, newid() as id
from #tblQuestions q
where q.moduleexamID=20
order by id
go