php - SQL SUM values from column and dividide by number of rows

492

I'm trying to calculate a percentual...and I need to sum all values from a column (Its already ok) but I need divide the result by number of rows...

 select sum(voto) from tablename where id = numberHere
817

Answer

Solution:

useCOUNT to get the totalNumber of rows.

SELECT SUM(voto) / (COUNT(*) * 1.0) 
FROM   tablename 
WHERE  id = numberHere

by adding* 1.0 on the query will allow decimal places on the result.

or simply as

SELECT AVG(voto)
FROM   tablename 
WHERE  id = numberHere
983

Answer

Solution:

JW's answer is correct if you're looking specifically to do it by Summing/Dividing, but SQL has a function for that.

SELECT AVG(voto) FROM tablename WHERE id = numberHere

AFAIK, it automatically returns the same type as you input (except date columns, which should be parsed to seconds then re-encoded to date).

788

Answer

Solution:

AVG should work, count(*) should work, you can also use @@rownum to get the number of rows returned by the statement if you need to do more with that number.

People are also looking for solutions to the problem: php - Doctrine 2 association inheritance with different classes

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.