- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL query to calculate the average of values in a row?
To calculate the average of values in a row in MySQL, use the following syntax
SELECT (yourTableName.yourColumnName1+yourTableName.yourColumnName2+yourTableName.yourColumnName3+,..........N)/numberOfColumns AS anyAliasName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table calculateAverageDemo -> ( -> x int, -> y int, -> z int -> ); Query OK, 0 rows affected (1.41 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into calculateAverageDemo values(10,20,30); Query OK, 1 row affected (0.78 sec) mysql> insert into calculateAverageDemo values(40,50,70); Query OK, 1 row affected (0.26 sec) mysql> insert into calculateAverageDemo values(80,90,220); Query OK, 1 row affected (0.43 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from calculateAverageDemo;
The following is the output
+------+------+------+ | x | y | z | +------+------+------+ | 10 | 20 | 30 | | 40 | 50 | 70 | | 80 | 90 | 220 | +------+------+------+ 3 rows in set (0.00 sec)
Here is the query to calculate average of values in a row
mysql> select (calculateAverageDemo.x+calculateAverageDemo.y+calculateAverageDemo.z)/3 -> AS Average from calculateAverageDemo;
The following is the output
+----------+ | Average | +----------+ | 20.0000 | | 53.3333 | | 130.0000 | +----------+ 3 rows in set (0.06 sec)
Advertisements