Calculate average of column from MYSQL query

2020-06-06 08:46发布

问题:

I've got a table that I am trying to calculate the average of the values in a column. Here is my lookup:

SELECT SUM(P1_Score) AS value_sum FROM tblMatches Where P1_ID LIKE $playerID

Any idea how I can determine the average (sum of values / total rows)?

回答1:

You can use AVG like so:

SELECT AVG(P1_Score)


回答2:

So in your case:

$gameswon = mysql_query("SELECT AVG(P1_Score) AS value_sum 
                         FROM tblMatches 
                         WHERE P1_ID LIKE '".$playerid."'");


回答3:

Try using AVG() aggregate function instead of SUM

$gameswon = mysql_query("SELECT AVG(P1_Score) AS value_sum FROM tblMatches Where P1_ID LIKE '".$playerid."' . "GROUP BY XXXX");

and XXXX is the column that you want to get average for such as player