MySQL Daily Average over a month
Translations
Englishالعربية
български
català
中文
čeština
dansk
Nederlands
eesti
suomi
français
Deutsch
Ελληνικά
עברית
हिंदी
magyar
Bahasa Indonesia
italiano
日本語
한국어
latviešu
lietuvių
norsk
polski
Português
română
русский
slovenčina
slovenski
español
svenska
ไทย
Türkçe
українська
Tiếng Việt
I'm pulling several status over a specific time period and I'd like to pull another stat that would be "average sales per day" over this time period. I'm not sure how to do daily averages over a specific time period, can anyone provide some advice?
$whereSql = 'WHERE created >= '.$endTimestamp.' AND
created <= '.$startTimestamp;
$tru->query->run(array(
'name' => 'get-figures',
'sql' => 'SELECT
SUM(price) AS total_sales,
COUNT(id) AS total_orders,
AVG(total) AS order_total_average
(SELECT
SUM(quantity)
FROM `order_product`
INNER JOIN `order` ON (
`order`.id = order_product.order_id AND
`order`.created >= '.$endTimestamp.' AND
`order`.created <= '.$startTimestamp.' AND
`order`.type_id = '.$type->getId().'
)
) as total_units
FROM `order`
'.$whereSql.' AND type_id = '.$type->getId().'',
'connection' => 'store'
));
This question and answers originated from www.stackoverflow.com
Question by Webnet (6/21/2010 12:04:23 AM)
Answer |
If I understand what you want correctly, you can just divide total sales by the number of days in the selected time period. Add this column to the outer select statement:
SUM(price)/DATEDIFF($endTimestamp,$startTimestamp)
Also make sure you are escaping user-supplied values with mysql_real_escape_string, otherwise you will have SQL injection vulnerabilities.
Answer by Krzysztof Kosiński
Find More Answers