What is the best way to calculate sum and percentage of data from database in PHP?
Use PHP and MySQL, my tab开发者_开发问答le is something like that, 1st field 'id', 2nd field 'score' and etc. I want to get the scores from rows which id<20 and also want sum of scores for all rows and percentages for score in each row. Does it has other way to get sum and percentages from table rather than calculate by PHP statement outside sql statement?
"SELECT score FROM Table WHERE id<20";
then use PHP statement to calculate sum and pertages.
Help me please
SELECT sum(score) FROM Table WHERE id<20
Will give you the total sum of scores.
Another SQL can give you the percentages for each id:
SELECT id, 100.0 / :total * score FROM Table WHERE id<20
Whereaes :total is the total value you got from the first statement (I'm not sure of the exact syntax of doing this in PHP).
If you're not interested in the total, only the percentages, you can combine the both queries:
SELECT id, 100.0 / (SELECT sum(score) FROM Table WHERE id<20) * score FROM Table WHERE id<20
Would this work?
SELECT SUM(score) FROM Table WHERE id<20
It's better to leave these calculations up to database:
SELECT SUM(score) FROM Table WHERE id<20
e.g. These will calculate the sum of scores.
What about using the SUM()
function?
Like this:
SELECT SUM(score) FROM Table WHERE id<20
精彩评论