开发者

Help calculating average per day

The daily_average column is always returning zero. The default timestamp values are for the past week. Any thoughts on what I'm doing wrong here in getting the average order value per day?

SELECT
    SUM(price+shipping_price) AS total_sales,
    COUNT(id) AS total_orders,
    AVG(price+shipping_price) AS order_total_average,
    (SELECT
            SUM(quantity)
        FROM `order_product`
        INNER JOIN `order` ON (
            `order`.id = order_product.order_id AND
            `order`.created >= '.$startTimestamp.' AND
            `order`.created <= '.$endTimestamp.' AND
            `order`.type_id = '.$ty开发者_JAVA技巧pe->getId().' AND
            `order`.fraud = 0
        )
    ) as total_units,
    SUM(price+shipping_price)/DATEDIFF('.$endTimestamp.', '.$startTimestamp.') as daily_average
FROM `order`
WHERE created >= '.$startTimestamp.' AND
created <= '.$endTimestamp.' AND
fraud = 0 AND
type_id = '.$type->getId().'


You're using aggregate functions (SUM, COUNT, AVG) without an aggregate command (group by). I think your SQL is more complicated than it needs to be (no need for the inner select).

Here's a SQL command that should work (hard to test without test data ;))

SELECT 
  COUNT(id) total_orders,
  SUM(finalprice) total_sales,
  AVG(finalprice) order_average,
  SUM(units) total_units,
  SUM(finalprice)/DATEDIFF('.$endTimestamp.', '.$startTimestamp.') daily_average
FROM (
  SELECT
    o.id id,
    o.price+o.shipping_price finalprice,
    SUM(p.quantity) units
  FROM order o INNER JOIN order_product p ON p.order_id=o.id
  WHERE o.created>='.$startTimestamp.' 
    AND o.created<='.$endTimestamp.'
    AND o.fraud=0
    AND o.type_id='.$type->getId().'
  GROUP BY p.order_id
) t;


Does casting one of the elements in the division work for you?

SELECT
    SUM(price+shipping_price) AS total_sales,
    COUNT(id) AS total_orders,
    AVG(price+shipping_price) AS order_total_average,
    (SELECT
        SUM(quantity)
        FROM `order_product`
        INNER JOIN `order` ON (
        `order`.id = order_product.order_id AND
        `order`.created >= '.$startTimestamp.' AND
        `order`.created <= '.$endTimestamp.' AND
        `order`.type_id = '.$type->getId().' AND
        `order`.fraud = 0
        )
    ) as total_units,
    CAST(SUM(price+shipping_price) AS float)/DATEDIFF('.$endTimestamp.', '.$startTimestamp.') as daily_average
FROM `order`
WHERE created >= '.$startTimestamp.' AND
created <= '.$endTimestamp.' AND
fraud = 0 AND
type_id = '.$type->getId().'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜