tags:

views:

30

answers:

2

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'
    ));
A: 

you will need to group by a to_char of the date that is scoped to the day (perhaps 'ddd') and you will need a where clause component that restricts to the proper date range

Randy
A: 

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.

Krzysztof Kosiński