试图从mysql获取上个月的数据

时间:2015-09-24 05:38:50

标签: php mysql sql

我试图从mysql调用上个月的数据,但它也提供了前几年的数据,例如2011年8月,2012年8月...... 2015年8月。我使用不同的函数来获取上个月的间隔但没有成功。这意味着来自数据库的订单总和也是不正确的。

查询1:

SELECT sku,
       order_date,
       sum(`order_total`) AS sales
FROM `tableOrder`
WHERE `order_status`='Shipped'
  AND MONTH(STR_TO_DATE(order_date, '%m/%d/%Y')) = MONTH(CURDATE() - INTERVAL 1 MONTH)
GROUP BY STR_TO_DATE(order_date, '%m/%d/%Y')
ORDER BY sales DESC

查询2:

SELECT sku,
       order_date,
       sum(`order_total`) AS sales
FROM `tableOrder`
WHERE `order_status`='Shipped'
  AND MONTH(STR_TO_DATE(order_date, '%m/%d/%Y')) = MONTH(DATE_ADD(Now(), INTERVAL -1 MONTH))
GROUP BY STR_TO_DATE(order_date, '%m/%d/%Y')
ORDER BY sales DESC

1 个答案:

答案 0 :(得分:0)

为年度添加额外条件:

SELECT sku,order_date,sum(`order_total`) as sales FROM `tableOrder` 
WHERE `order_status`='Shipped' 
    AND MONTH(STR_TO_DATE( order_date, '%m/%d/%Y' )) = MONTH(CURDATE() - INTERVAL 1 MONTH) 
    AND YEAR(order_date) = YEAR(NOW())
GROUP BY STR_TO_DATE( order_date, '%m/%d/%Y' ) 
ORDER BY sales desc