我有一张桌子
车
id | person_id | mpg
------------------------
4 | 1 | 50
5 | 1 | 15
6 | 2 | 10
7 | 2 | 28
8 | 3 | 33
我需要得到每个人mpg的平均值,然后是该组的平均值。
person 1 avg = (50 + 15) / 2 = 32.5
person 2 avg = (10 + 28) / 2 = 19
person 3 avg = 33
group average = 32.5 + 19 + 33 / 3 = 28.1
是否有可以满足我需要的查询?
答案 0 :(得分:5)
SELECT person_id, AVG(mpg) from car group by person_id;
如果你想获得该组的平均值,你应该这样做:
SELECT AVG(mpg) from car;
除非你真的想平均平均值,这对我来说似乎有点可疑:
SELECT AVG(average) from (SELECT person_id, AVG(mpg) as average from car group by person_id);
答案 1 :(得分:2)
你无法在1个查询中解决这个问题,但你必须使用2个查询或1个查询来解决代码中的总体平均值
select person, avg(mpg) from cat group by person
答案 2 :(得分:1)
SELECT person_id, AVG(mpg) AS mpg_avg FROM car GROUP BY person_id WITH ROLLUP
WITH ROLLUP
- 修饰符会在persion_id
为NULL
的结果集中添加一行,mpg_avg
是整个结果集的平均值(MySQL> = 4.1.1):
person_id | mpg
------------------
1 | 32.5
2 | 19.0
3 | 33.0
NULL | 27.2