与上个月相比的平均值

时间:2015-10-14 07:44:38

标签: mysql sql

我对从查询日期到发送日期的平均持续时间进行了SQL查询。这是我的电子商务项目。但我希望将它与上个月进行比较。

SELECT AVG(DATEDIFF(os.time, o.ordered)) AS average_value, 
       YEAR(os.time) AS groupYear, 
       MONTH(os.time) AS groupMonth 
FROM orders AS o 
       LEFT JOIN order_status_history os ON o.id = os.order_id 
WHERE  os.status_id = 2 
GROUP BY groupyear, groupmonth 

我也希望从上个月选择平均值。我在ON -1个月尝试LEFT JOIN。但它显示了不好的价值,所以它可能不是正确的方式。

o.ordered和os.time都是Datetime。

感谢大家的帮助。

2 个答案:

答案 0 :(得分:1)

这未经过测试。如果它不起作用,你可以发布一些抽样数据并创建语句

SELECT AVG(DATEDIFF(os.time, o.ordered)) AS average_value, 
       YEAR(os.time) AS groupYear, 
       MONTH(os.time) AS groupMonth 
FROM orders AS o
LEFT JOIN order_status_history os ON o.id = os.order_id 
LEFT JOIN (
            SELECT AVG(DATEDIFF(os.time, o.ordered)) AS average_value, 
                   YEAR(os.time) AS groupYear, 
                   MONTH(os.time) AS groupMonth 
            FROM orders AS o
            LEFT JOIN order_status_history os ON o.id = os.order_id 
            WHERE  os.status_id = 2 
            GROUP BY DATE_FORMAT(os.`time`, '%Y%my')
          ) AS l ON l.groupYear = YEAR(SUBDATE(os.time, INTERVAL 1 MONTH)) AND l.groupMonth = MONTH(SUBDATE(os.time, INTERVAL 1 MONTH))
WHERE  os.status_id = 2 
GROUP BY DATE_FORMAT(os.`time`, '%Y%my');

答案 1 :(得分:0)

我的解决方案是首先为子查询创建一个视图:

CREATE VIEW MonthlyValue AS        
SELECT YEAR(os.time) AS groupYear, 
       MONTH(os.time) AS groupMonth, 
       os.status_id,
       AVG(DATEDIFF(os.time, o.ordered)) AS average_value
FROM orders AS o 
      LEFT JOIN order_status_history os ON o.id = os.order_id 
GROUP BY groupyear, groupmonth,os.status_id;

然后,您可以使用该视图获取上一个月和当前月份的信息:

SELECT tc.groupYear as year, tc.groupMonth as month, tp.groupYear prevYear, tp.groupMonth as prevMonth,
    mv.average_value, mvprev.average_value, mv.average_value - mvprev.average_value as difference
FROM MonthlyValue mv join MonthlyValue mvprev on mv.status_id=mvprev.status_id and
     (mv.groupYear=mvprev.groupYear and mvprev.groupMonth=mv.groupMonth-1 or 
            mv.groupMonth=1 and mvprev.groupMonth=12 and mvprev.groupYear=mv.groupYear-1)
WHERE mv.status_id = 2;