按上个月SQL查询

时间:2019-02-22 15:16:57

标签: mysql sql

我想在上个月之前返回此查询。

我的表 service_total 作为字段 date_time ,我想使用该表。

我正在对此进行搜索,并尝试了多种方法。但是我无法获得正确的语法。

SELECT service_total.total_shipments , partner.name
FROM service_total
INNER JOIN partner 
ON partner.short = service_total.partner_short
WHERE partner.local = '0' 
ORDER BY service_total.total_shipments DESC
LIMIT 5

编辑------------

有关查询是正确的,但我希望仅返回上个月的值。

想象在表 service_total 中,我有2行。一是从十二月开始,一是从一月开始。从2月开始,我只希望从1月开始的那一行。

2 个答案:

答案 0 :(得分:1)

您需要在声明中包括以下条件:

  YEAR(date_time) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
  AND 
  MONTH(date_time) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)

所以:

SELECT service_total.total_shipments , partner.name
FROM service_total
INNER JOIN partner 
ON partner.short = service_total.partner_short
WHERE 
  YEAR(date_time) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
  AND 
  MONTH(date_time) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)  
  AND
  partner.local = '0'  
ORDER BY service_total.total_shipments DESC
LIMIT 5

答案 1 :(得分:0)

在条件

中使用date_time
 SELECT service_total.total_shipments , partner.name
    FROM service_total
    INNER JOIN partner 
    ON partner.short = service_total.partner_short
    WHERE partner.local = '0'  and date_time >= date(NOW() - INTERVAL 1 MONTH)
    ORDER BY service_total.total_shipments DESC
    LIMIT 5