简体   繁体   English

SQL选择上个月的数据

[英]SQL Select data from previous month

I am able using the code below to select data from any number of days in the past but what if I only want the data from the previous month, eg from 60 days ago to 30 days ago. 我可以使用下面的代码选择过去任意几天的数据,但是如果我只想要上个月的数据(例如60天之前到30天之前),该怎么办。

I thought I might be able to use INTERVAL 60 - 30 , but I am not sure that is working... 我以为我也许可以使用INTERVAL 60 - 30 ,但是我不确定这是否可行...

SELECT
    product,
    COUNT(OrderNumber) AS CountOf
FROM
    orders
WHERE
    STATUS = 'booking' AND
    Date(OrderDate) <= CURDATE() AND 
    Date(OrderDate) > DATE_SUB(CURDATE(),INTERVAL 30 DAY)

GROUP BY
    product
ORDER BY CountOf DESC

Thoughts? 有什么想法吗?

This is too long for a comment: 此评论太长了:

Date(OrderDate) < DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND 
Date(OrderDate) >= DATE_SUB(CURDATE(), INTERVAL 60 DAY)

Note: if OrderDate is already a date, then don't use the DATE() function. 注意:如果OrderDate已经是一个日期,则不要使用DATE()函数。 It can prevent the use of indexes. 它可以防止使用索引。

Even if OrderDate has a time component, you probably still don't need the DATE() function. 即使OrderDate具有时间成分,您可能仍然不需要DATE()函数。

Do you know about the MySQL functions MONTH() and NOW() ? 您知道MySQL函数MONTH()NOW()吗? You can use these in your where clause: 您可以在where子句中使用它们:

MONTH(OrderDate) = MONTH(NOW()) - 1

Of course, this needs to be fine tuned for example for years (to get December if it is January). 当然,例如,这需要多年进行微调(如果是1月,则要获得12月)。

我相信DATE_SUB()函数支持将MONTH用作间隔,因此,如果您希望从当前日期起获取上个月的数据,则应该可以使用MONTH

Date(OrderDate) > DATE_SUB(CURDATE(),INTERVAL 1 MONTH)

You can use something like this 你可以用这样的东西

SELECT
    product,
    COUNT(OrderNumber) AS CountOf
FROM
    orders
WHERE
    STATUS = 'booking' AND
    YEAR(orderdate) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
    AND MONTH(orderdate) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)   
GROUP BY
    product
ORDER BY CountOf DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM