简体   繁体   中英

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 = '.$type->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().'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM