Average on a count() in same query

前端 未结 1 759
借酒劲吻你
借酒劲吻你 2020-12-30 00:03

I\'m currently working on an assignment which requires me to find the average on the number of resources for each module. The current table looks like this:

         


        
相关标签:
1条回答
  • 2020-12-30 00:36

    This is the query you are executing, written in a slightly less obtuse syntax.

    SELECT
      avg(a.ress) as GjSnitt
      , modulID
    FROM
      (SELECT COUNT(ressursID) as ress 
       FROM ressursertiloppgave
       GROUP BY modulID) as a
    CROSS JOIN ressursertiloppgave r    <--- Cross join are very very rare!
    GROUP BY modulID;
    

    You are cross joining the table, making (6x6=) 36 rows in total and condensing this down to 4, but because the total count is 36, the outcome is wrong.
    This is why you should never use implicit joins.

    Rewrite the query to:

    SELECT AVG(a.rcount) FROM 
      (select count(*) as rcount 
       FROM ressursertiloppgave r
       GROUP BY r.ModulID) a
    

    If you want the individual rowcount and the average at the bottom do:

    SELECT r1.ModulID, count(*) as rcount
    FROM ressursertiloppgave r1
    GROUP BY r1.ModulID 
    UNION ALL 
      SELECT 'avg = ', AVG(a.rcount) FROM 
      (select count(*) as rcount 
       FROM ressursertiloppgave r2
       GROUP BY r2.ModulID) a
    
    0 讨论(0)
提交回复
热议问题