попробуйте захватить количество строк на INSERT, а затем выберите строку, которая находится в середине, используя ROW_NUMBER ():
CREATE TABLE #QuizTemp (QuizProfileID INT,Cnt INT,TotalScore INT)
DECLARE @Rows int
INSERT INTO #QuizTemp
SELECT QuizAnswers.QuizProfileID, COUNT(QuizAnswers.QuizProfileID) AS Cnt, SUM(QuizAnswers.AnsweredYes) As TotalScore
FROM QuizAnswers INNER JOIN
Quizzes ON QuizAnswers.QuizID = Quizzes.QuizID
WHERE (Quizzes.PartnerID = 16)
GROUP BY QuizAnswers.QuizProfileID
HAVING COUNT(QuizAnswers.QuizProfileID)= 5
DECLARE @Rows int
SELECT @Rows=@@Rowcount
;with allrows as
(
SELECT TotalScore, ROW_NUMBER() (ORDER BY TotalScore) AS RowNumber
)
SELECT @Rows AS CNT, TotalScore AS MedianScore
FROM allrows WHERE RowNumber=@Rows/2
DROP TABLE #QuizTemp
EDIT
Вот решение без временной таблицы:
DECLARE @YourTable table (TotalScore int)
INSERT INTO @YourTable Values (1)
INSERT INTO @YourTable Values (2)
INSERT INTO @YourTable Values (3)
INSERT INTO @YourTable Values (40)
INSERT INTO @YourTable Values (50)
INSERT INTO @YourTable Values (60)
INSERT INTO @YourTable Values (70)
;with allrows as
(
SELECT
TotalScore, ROW_NUMBER() OVER (ORDER BY TotalScore) AS RowNumber
FROM @YourTable
)
,MaxRows AS
(SELECT MAX(RowNumber) AS CNT,CONVERT(int,ROUND(MAX(RowNumber)/2.0,0)) AS Middle FROM allrows)
SELECT
m.CNT
,(SELECT AVG(TotalScore) FROM allrows) AS AvgTotalScore
,a.TotalScore AS Median
,m.Middle AS MedianRowNumber
FROM allrows a
CROSS JOIN MaxRows m
WHERE a.RowNumber=m.Middle
ВЫВОД:
CNT AvgTotalScore Median MedianRowNumber
-------------------- -------------------- ----------- --------------------
7 32 40 4
(1 row(s) affected)
если вы редактируете первый CTE так:
;with allrows as
(
SELECT QuizAnswers.QuizProfileID, COUNT(QuizAnswers.QuizProfileID) AS Cnt, SUM(QuizAnswers.AnsweredYes) As TotalScore
, ROW_NUMBER() OVER (ORDER BY TotalScore) AS RowNumber
FROM QuizAnswers INNER JOIN
Quizzes ON QuizAnswers.QuizID = Quizzes.QuizID
WHERE (Quizzes.PartnerID = 16)
GROUP BY QuizAnswers.QuizProfileID
HAVING COUNT(QuizAnswers.QuizProfileID)= 5
)
должно работать по вашему запросу