帮助计算每天的平均值

时间:2011-02-25 15:00:07

标签: mysql

daily_average列始终返回零。默认时间戳值是过去一周。在获取每日平均订单价值方面,我对此做错了什么?

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

2 个答案:

答案 0 :(得分:0)

您正在使用聚合函数(SUMCOUNTAVG)而没有聚合命令(分组依据)。我认为你的SQL比它需要的更复杂(不需要内部选择)。

这是一个应该工作的SQL命令(很难在没有测试数据的情况下进行测试;))

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;

答案 1 :(得分:0)

在该部门中投射其中一个元素是否适合您?

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