Returning records from the last 3 months only in MySQL

后端 未结 4 1337
野性不改
野性不改 2020-12-01 07:35

I have a table with a timestamp field. How do I get data from the last 3 months?

In particular, March is my current month let say, 03/2012. I need to retur

相关标签:
4条回答
  • 2020-12-01 08:14

    3 months before today:

    select * from table where timestamp >= now()-interval 3 month;
    

    Start with first of month:

    select * from table where timestamp >= last_day(now()) + interval 1 day - interval 3 month;
    
    0 讨论(0)
  • 2020-12-01 08:26

    To get the first day of the current month, you could use this:

    DATE_FORMAT(CURDATE(), '%Y-%m-01')
    

    if current date is 2013-03-13, it will return 2013-03-01, and we can just substract 2 months from this date to obtain 2013-01-01. Your query could be like this:

    SELECT *
    FROM yourtable
    WHERE data >= DATE_FORMAT(CURDATE(), '%Y-%m-01') - INTERVAL 2 MONTH
    
    0 讨论(0)
  • 2020-12-01 08:26

    Assuming you're using SQL Server (Oracle, MySQL and others have similar date functions), you can use the dateadd function to add or subtract an interval to the current date.

    If you want a full three months, you can subtract 3 months from today : DATEADD(m,-3,getdate())

    But, as you state, you only want data from January, February and March. You have to make some calculation based on today's date: dateadd(m,-2, CONVERT(datetime, CONVERT(VARCHAR(2), MONTH(getdate())) + '/01/' + CONVERT(VARCHAR(4), YEAR(getdate()))))

    And in the end, get a query like

    SELECT fields 
    FROM table 
    WHERE timestampfield > DATEADD(m,-2, CONVERT(datetime, CONVERT(VARCHAR(2), MONTH(getdate()))  + '/01/' + CONVERT(VARCHAR(4), YEAR(getdate()))))
    

    --- edit --- erf, I just noticed the "mysql" tag... you can get more information on MySQL date functions here : https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

    0 讨论(0)
  • 2020-12-01 08:32

    I know this is an old question, but to possibly save others time and to sum the above answers up for the case of needing (1) dates from current month and (2) dates from the prior 2 months (common when displaying data statistics):

    WHERE ((timestamp >= NOW() - DATE_FORMAT(CURDATE(), '%Y-%m-01'))
    OR  (timestamp >= DATE_FORMAT(CURDATE(), '%Y-%m-01') - INTERVAL 2 MONTH))
    
    0 讨论(0)
提交回复
热议问题