3

This may be very simple but I am trying to do a query that will return the average of the results but I also want it to count the number of rows it used to get the average. For example:

Row 1 = 5
Row 2 = 2
Row 3 = 9
Row 4 = 1

Average = 4.25
Count = 4

Is there a way to do this with one query apposed to two. When i used the avg function is always just returns one row so my count is 1 instead of 4. I need a query that will average but also tell me how many records it went through.

I am trying to avoid using two queries. Thank you for your help.

4 Answers 4

7

This is pretty basic and should have been discoverable via search.

SELECT COUNT(field) as `count`, AVG(field) as `average` FROM table_name
Sign up to request clarification or add additional context in comments.

Comments

1

In the terms you have stated - if you aren't GROUPing or things like that - you'd just write

SELECT COUNT(col) AS cnt, AVG(col) AS avg FROM tbl;

and you ought to have no problems. You get one row, with the fields cnt and col containing what you need.

The problem you're having is probably due to the use of mysql_num_rows to get the count, which is not correct. forgot to add: or to the fact that you did not supplied your whole problem.

Comments

0

You can use multiple aggregate functions in a single query:

SELECT COUNT(*), AVG(field) FROM mytable

Comments

0
SELECT COUNT(*), AVG(YourColumn)
    FROM YourTable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.