Search code examples
sqlpostgresqlaggregation

Calculate number of people over average


I am trying to calculate how many people have a grade higher than average.
What I have currently instead returns the number of students and when I delete "=" from ">=" it returns 0.

SELECT count(*) 
FROM data.students
WHERE grade IN (SELECT grade 
               FROM data.students
               GROUP BY grade HAVING grade >= AVG(grade));

If I put an integer instead of avg() function I get good results. What am I doing wrong?


Solution

  • Computing the avg in a subquery is probably fastest:

    SELECT count(*)
    FROM   data.students
    WHERE  grade > (SELECT avg(grade) FROM data.students);
    

    > instead of >=, since you said "a grade higher than average".

    What am I doing wrong?

    In your subquery, GROUP BY grade aggregates to one row per distinct value of grade. avg(grade) is bound to be exactly the same as grade for every row (except grade IS NULL). Explains what you saw.
    Your query was needlessly complex to begin with.