同一查询中count()的平均值

时间:2011-10-25 17:54:26

标签: mysql

我正在进行一项任务,要求我找到每个模块的资源数量的平均值。当前表格如下:

ResourceID   ModulID
   1            1
   2            7
   3            2
   4            4
   5            1
   6            1

基本上,我正在试图弄清楚如何获得平均资源数量。唯一的 这里的相关测试数据是模块1,它有3个不同的资源连接到它。但我需要显示所有结果。

这是我的代码:

select avg(a.ress) GjSnitt, modulID
from 
(select count(ressursID) as ress 
 from ressursertiloppgave
 group by modulID) as a, ressursertiloppgave r
group by modulID;

显然它不起作用,但我目前正处于失去改变的地步。我非常感谢你们有任何意见。

1 个答案:

答案 0 :(得分:34)

这是您正在执行的查询,用稍微不那么钝的语法编写。

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;

你正在交叉加入表格,共计(6x6 =)36行并将其缩减为4,但由于总计数为36,结果是错误的。
这就是你永远不应该使用隐式连接的原因。

将查询重写为:

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

如果您想要个人行数底部的平均值,请执行以下操作:

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