0

Edit: Deleted my old message cause it was confusing. And i can't answer my own question for now.

Found, problem come from GROUP BY.

After some researches, i found that we can't use GROUP BY for group a column inside grouped rows.

So this work as expected :

SELECT candidats.*
      , AVG(test_results.rate_good_answer) AS toto
  FROM "candidats" 
LEFT JOIN "sessiontests"
  ON "sessiontests"."candidat_id" = "candidats"."id"  
LEFT JOIN "test_results"
  ON "test_results"."sessiontest_id" = "sessiontests"."id" 
LEFT JOIN "questionnaires"
  ON "questionnaires"."id" = "test_results"."questionnaire_id"  
WHERE (sessiontests.terminate = 't' )
  AND ("questionnaires"."category" LIKE '%java%' ) 
GROUP BY candidats.id 
ORDER BY toto

But this will grouped only my column in test_results :

SELECT candidats.*, 
  FROM "candidats" 
LEFT JOIN "sessiontests"
  ON "sessiontests"."candidat_id" = "candidats"."id"  
LEFT JOIN "test_results"
  ON "test_results"."sessiontest_id" = "sessiontests"."id" 
LEFT JOIN "questionnaires"
  ON "questionnaires"."id" = "test_results"."questionnaire_id"  
WHERE (sessiontests.terminate = 't' )
 AND ("questionnaires"."category" LIKE '%java%' ) 
GROUP BY candidats.id, test_results.rate_good_answer 
ORDER BY AVG(test_results.rate_good_answer)

Edit 3 :

My problem was the second query was returning each different test_results row for my candidats, whereas i expected it to return me one line per candidat.

First query, is the answer, and it works nice.

3
  • Have you tried grouping on "candidats"."id" instead? Oct 19, 2011 at 8:53
  • Can you clarify how you want to sort the results, possibly by including examples? Sorting by an average (or any other aggregate function) will always leave the results unsorted within their groups, since an aggregate function will always have the same value within the group. Also, are you using MySQL?
    – user359040
    Oct 19, 2011 at 9:03
  • Just tried, it crashed my sqlite :p. But i already knew, it wasn't going to work. Because, if you want to use an aggregate function in your ORDER BY, you have to GROUP BY this column. @Mark, currently my problem is solved. My question was really confusing, so i just add the answer. My first query works as expected.
    – Perello
    Oct 19, 2011 at 9:05

1 Answer 1

0

SELECT candidats.* , AVG(test_results.rate_good_answer) AS toto FROM "candidats" LEFT JOIN "sessiontests" ON "sessiontests"."candidat_id" = "candidats"."id"
LEFT JOIN "test_results" ON "test_results"."sessiontest_id" = "sessiontests"."id" LEFT JOIN "questionnaires" ON "questionnaires"."id" = "test_results"."questionnaire_id"
WHERE (sessiontests.terminate = 't' ) AND ("questionnaires"."category" LIKE '%java%' ) GROUP BY candidats.id ORDER BY toto

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.