简体   繁体   English

如何选择字段mysql中最后日期之前的最后n个月?

[英]how to select last n month before the last date in field mysql?

I have a question with mysql. 我对mysql有疑问。 I have a table like records and records have a field registered_date which contains the dates. 我有一个类似记录的表,记录有一个包含日期的字段registered_date。 I want to select last n months but not before the current date. 我想选择过去n个月,但不要在当前日期之前。 I must select the last date that registered_date contains. 我必须选择registered_date包含的最后日期。

registered_date 登记日期

  • 2015-05-30 2015-05-30
  • 2015-05-29 2015-05-29
  • 2015-05-28 2015-05-28
  • 2015-05-27 2015-05-27
  • ... ...

and we are in july. 我们在七月。 The last date is 2015-05-30. 最后日期是2015-05-30。 I want to select last 3 months before the 2015-05-30. 我想选择2015-05-30前的最后3个月。

I tried to like these: 我试图喜欢这些:

 .... where registered_date > DATE_SUB(now(), INTERVAL 6 MONTH)

and

registered_Date between now() - interval 30 day and now()

Thank you. 谢谢。

You need to find the biggest date and then select three months before that: 您需要找到最大的日期,然后在此之前选择三个月:

select t.*
from table t cross join
     (select max(registered_date) as maxrd from table t) m
where t.registered_date >= maxrd - interval 3 month;

你这样尝试过吗

SELECT * FROM table WHERE registered_date >= now()-interval 3 month;

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

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