I need to show monthly average of total using SQL and PHP. For example this table has total=254 in June & total=315 in July. I need to show their average i.e. (254+315)/2= 284.5
What SQL query should I make to print their average using PHP?
Advertisement
Answer
One method is:
select sum(total) / count(distinct extract(year_month from date)) from t;
This sums the total
column and divides by the number of months. If you need this for the particular two months, then include a where
clause:
select sum(total) / count(distinct extract(year_month from date)) from t where date >= '2020-06-01' and date < '2020-08-01'
If you wanted to count missing months as 0
for the average purposes, then use a constant:
select sum(total) / 2 from t where date >= '2020-06-01' and date < '2020-08-01'