I have a simple query which finds the average answers to questions in a survey. The structure is as follows: |Questions |Answers |Participants |Surveys |------------ |--------- |-------------- |-------- |QuestionId |QuestionId |ParticipantId |SurveyId |SurveyId |ParticipantId |SurveyId |... |... |Answer |...
The query to get the average answer for a specific survey ID is:SELECT AVG(CAST(a.Answer AS float)) AS AvgAnsFROM Answers aINNER JOIN Questions q ON a.QuestionId = q.QuestionId INNER JOIN Participants p ON a.ParticipantId = p.ParticipantIdWHERE (p.SurveyId = 123)
This works as expected, and returns the answer in about 0.0 seconds, according to query analyser.However, when I use the above query in an ORDER BY clause, the entire query takes several seconds to complete - ordering only a handful on selected survey IDs. For example:SELECT s.SurveyId FROM Surveys sWHERE (s.SurveyId IN(1061,1075,1079,1084,1088,1112,1187,1192,1197,1206,1208,1210,1211,1105,1095))ORDER BY(SELECT AVG(CAST(a.Answer AS float)) AS AvgAnsFROM Answers aINNER JOIN Questions q ON a.QuestionId = q.QuestionId INNER JOIN Participants p ON a.ParticipantId = p.ParticipantIdWHERE (p.SurveyId = s.SurveyId))
The above query takes a couple of seconds. This seems weird, considering each individual AVG calculation only takes a split second (0:00 seconds in QA), and I'm only going through a handful of surveys.Is there a better way to approach sorting data by a subquery like this?