Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query sum result divide by number of row (Average)

I have following data in MySQL and i want to sum (total) and then divide by number for row.

Example:

I want to sum all number in AcctSessionTime column and divide that with number of items so in our case 6+4+3+31=44 divide them with 4 number of row.

How do i craft query to do all in single query?

mysql> select AcctStartTime,AcctStopTime,AcctSessionTime 
       from radacct 
       where UserName='spatel' AND SipResponseCode='200';
+---------------------+---------------------+-----------------+
| AcctStartTime       | AcctStopTime        | AcctSessionTime |
+---------------------+---------------------+-----------------+
| 2015-06-04 15:32:03 | 2015-06-04 15:32:09 |               6 |
| 2015-06-04 16:11:27 | 2015-06-04 16:11:31 |               4 |
| 2015-06-04 16:13:37 | 2015-06-04 16:13:40 |               3 |
| 2015-06-05 11:44:31 | 2015-06-05 11:45:02 |              31 |
+---------------------+---------------------+-----------------+
4 rows in set (0.00 sec)

Notes: above is example data we have actual data in thousands of rows.

like image 793
Satish Avatar asked Jan 18 '26 06:01

Satish


2 Answers

The calculation SUM(RowData) / #Rows is an Average of RowData - this is already supported natively as the AVG aggregate function:

select AVG(AcctSessionTime) 
from radacct 
where UserName='spatel' AND SipResponseCode='200';

You can also do grouped averages with a GROUP BY statement, if required

like image 167
StuartLC Avatar answered Jan 19 '26 20:01

StuartLC


mysql> select sum(AcctSessionTime) div count(AcctSessionTime) as result from radacct where UserName='spatel' AND SipResponseCode='200';

| result |
+--------+
|     11 |

You can try this.

like image 36
Navneet Avatar answered Jan 19 '26 18:01

Navneet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!