2013-10-30 44 views
1

我想在一個SQL命令中使用這兩個SQL語句。幫助:)選擇SUM然後用它作爲SELECT TOP的參數

聲明#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() 
+4

請不要喊叫 –

+0

的SQL Server的什麼版本? –

+0

MS SQL Server 2005 – eirishainjel

回答

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 
+1

謝謝你,先生。有用! – eirishainjel

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); 
+0

因爲'RN <= NULL'永遠不會成立,所以這種情況會返回0行。而用你的'ISNULL'包裝器,你會強制比較爲'RN <= 0',這將會*也永遠不會是真的 - 所以我不知道爲什麼你認爲這是必要的。 –

+0

@Damien_The_Unbeliever:你說得對,在這種情況下沒有必要,但我認爲這是明確的。 – valex

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