2011-02-25 133 views
0

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

什麼是startTimestamp和endTimestamp?時代以來的時間?格式化日期?如果格式化,如何? DATEDIFF需要日期而不是時間戳。如果從時代開始,FROM_UNIXTIME會有所幫助。 – justkt 2011-02-25 15:04:05

+0

你明白了嗎? – Rudu 2011-02-25 17:57:29

回答

0

您使用聚合函數(SUMCOUNTAVG)沒有aggregate命令(GROUP BY)。我認爲你的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; 
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().'