English 中文(简体)
平均数字
原标题:Averaging an average in mySQL
  • 时间:2009-11-18 12:42:20
  •  标签:
  • mysql

页: 1

汽车

 id |  person_id  |  mpg
------------------------  
 4  |     1       |  50
 5  |     1       |  15
 6  |     2       |  10
 7  |     2       |  28
 8  |     3       |  33

我需要获得每个人的体格,然后得到该群体的平均数。

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

是否有人问我需要做什么?

最佳回答
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个问询,解决你法典中的超平均数。

select person, avg(mpg) from cat group by person
SELECT person_id, AVG(mpg) AS mpg_avg FROM car GROUP BY person_id WITH ROLLUP

<代码>WITH ROLUP-modifier将添加一个行文,将persion_id改为NULmpg_avg为整个成果集(MySQL >= 4.1.1):

 person_id | mpg 
------------------
         1 | 32.5 
         2 | 19.0
         3 | 33.0
      NULL | 27.2




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...