Given the following sample data:
tblData
Date Sales
----------------------
2011-12-01 122
2011-12-02 433
2011-12-03 213
...
2011-12-31 235
2011-11-01 122
2011-11-02 433
2011-11-03 213
...
2011-11-30 235
2011-10-10 122
2011-10-11 433
2011-10-12 213
...
2011-10-31 235
Notice that October data begins at 10 October, whereas subsequent months have complete data.
I need to get the average monthly sales over all complete months, which in this case would be November and December 2011.
How would I do this?
Introduction to MySQL AVG() function You use the DISTINCT operator in the AVG function to calculate the average value of the distinct values. For example, if you have a set of values 1,1,2,3, the AVG function with DISTINCT operator will return 2 i.e., (1 + 2 + 3) / 3 .
MySQL AVG() function retrieves the average value of a given expression. If the function does not find a matching row, it returns NULL. Where expr is a given expression. The DISTINCT option can be used to return the average of the distinct values of expr.
The SQL AVG function calculates the average of a series of values that you provide to it. Most of the time, this will be a particular column that you specify, so the average will be all of the values in that column. Just like the MIN and MAX functions, the AVG function is a SQL standard column.
AVG() Function in MySQL This function in MySQL is used to return the average value of the specified expression. Features : This function is used to find the average value of the specified expression. This function comes under Numeric Functions. This function accepts only one parameter namely expression.
SELECT `date`, AVG(`sales`)
FROM sales
GROUP BY YEAR(`date`), MONTH(`date`)
HAVING COUNT(`date`) = DAY(LAST_DAY(`date`));
Example
If you want to limit the result, either
HAVING ...
ORDER BY `date` DESC LIMIT 3
which should always return data for the 3 most recent months, or something like
FROM ...
WHERE DATE_FORMAT(CURDATE() - INTERVAL 3 MONTH, '%Y-%m')
<= DATE_FORMAT(`date`, '%Y-%m')
GROUP BY ...
which should return data for the 3 previous months, if there is any. I'm not sure which is better but I don't believe WHERE
gets to use any index on date
, and if you're using DATETIME
and don't format it you'll also be comparing the days and you don't want that,
Can't test it right now, but please have a try with this one:
SELECT
DATE_FORMAT(`Date`, '%Y-%m') AS yearMonth,
SUM(Sales)
FROM
yourTable
GROUP BY
yearMonth
HAVING
COUNT(*) = DAY(LAST_DAY(`Date`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With