我有一个输入的问题表:Select One
, True False
,Select All
我正在尝试编写一个查询,该查询将返回一定数量的问题,同时将其中一种类型限制为返回的类型的特定百分比。
例子:
SELECT QuestionID, QuestionText, QuestionType
FROM Question
WHERE/HAVING --limit QuestionTypeID = 4 to be only 10% of total returned
我最初的想法是单独提取查询
SELECT TOP 10 PERCENT QuestionID, QuestionText, QuestionType
FROM Question
WHERE QuestionTypeID <> 4
UNION ALL
SELECT QuestionID, QuestionText, QuestionType
FROM Question
WHERE QuestionTypeID = 4
然而,似乎有一种更有效的计算方法。
编辑:
让我澄清一下我要完成的工作......我需要返回 90% 的其他类型问题的混合体,而只有 10% 的类型 4。
我需要将结果随机化,所以我一直在使用SET ROWCOUNT
和ORDER BY NEWID()
我可以使用子查询,但不确定在SET ROWCOUNT
子查询中使用的方式...此时似乎需要临时表,但如果有更好的方法请告诉我...
到目前为止我所拥有的......带有临时表
DECLARE @ReturnPercent [int] --variable that holds percentage for bottom questions
DECLARE @ReturnCount [int] --variable that holds how many questions I'd like returned
CREATE TABLE #Temp1(
QuestionID [int],
QuestionText [nvarchar](256),
QuestionTypeID [int]
);
DECLARE @TOP [int] = @ReturnCount-CAST(@ReturnCount*@ReturnPercent AS INT);
DECLARE @BOTTOM [int] = CAST(@ReturnCount(@ReturnPercent AS INT);
SET ROWCOUNT @TOP
INSERT INTO #Temp1(QuestionID, QuestionText, QuestionTypeID)
SELECT QuestionID, QuestionText, QuestionTypeID
FROM Question
WHERE QuestionTypeID <> 4
ORDER BY NEWID()
SET ROWCOUNT 0
SET ROWCOUNT @BOTTOM
INSERT INTO #Temp1(QuestionID, QuestionText, QuestionTypeID)
SELECT QuestionID, QuestionText, QuestionTypeID
FROM Question
WHERE QuestionTypeID = 4
ORDER BY NEWID()
SET ROWCOUNT 0
--Query to join them with other data(omitted)
SET ROWCOUNT @ReturnCount
SELECT a.QuestionID, a.QuestionText, a.QuestionTypeID
FROM #Temp1 a
JOIN --OTHER TABLES FOR FULL QUERY
ORDER BY NEWID()
SET ROWCOUNT 0