Hi Dev,
If you need to see example of how to display average of all rows of a column in php mysql. this example will help you mysql avg() function. you can see display average of data from database in php mysql. you'll learn average sql mysql avg tutorial. You just need to some step to done calculate get the average in php mysql.
In this article, we show how to get the average of all rows of a column of a MySQL table using PHP.
Example :
index.php
$sql = CREATE TABLE sales (
product varchar(255),
order_date date,
sale int
);
Insert some records in the table using insert command :
$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Laptop', '2022-11-01', 20);
$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Mobile', '2022-10-10', 25);
$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Mobile', '2022-08-12', 15);
$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Laptop', '2022-08-12', 30);
$sql = INSERT INTO sales (product, order_date, sale ) VALUES('Laptop', '2022-07-18', 20);
Display all records from the table using select statement :
select * from sales;
Output:
+---------+------------+------+
| product | order_date | sale |
+---------+------------+------+
| Laptop | 2022-11-01 | 20 |
| Mobile | 2022-10-10 | 25 |
| Mobile | 2022-08-12 | 15 |
| Laptop | 2022-08-12 | 30 |
| Laptop | 2022-07-18 | 20 |
+---------+------------+------+
If you want to calculate average sales per day for each product, then here’s an SQL query for it.
SELECT product, avg(sale) FROM sales by product;
Output:
+---------+-----------+
| product | avg(sale) |
+---------+-----------+
| Laptop | 23.3333 |
| Mobile | 20.0000 |
+---------+-----------+
I hope it could help you...
My name is Divyang Vadodariya. I'm a full-stack developer, entrepreneur and owner of CodeTheTrack. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap ,etc from the early stage.
Copyright © 2023 www.CodeTheTrack.com • All Rights Reserved