我想在一个 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()
我想在一个 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()
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
只需使用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);
您也可以尝试以下操作:
;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