简体   繁体   English

如何编写 where 子句以动态获取上个月某个日期和当前月份某个日期之间的日期?

[英]How can I write a where clause to get dates between some date in the last month and some date in the current month, dynamically?

I need to write a query where I need all the records between the 26th of last month and the 25th of the current month and if the current date is between 26 and 31 then I need records between 26 and 31 of just this month.我需要编写一个查询,我需要上个月 26 日和本月 25 日之间的所有记录,如果当前日期在 26 日到 31 日之间,那么我需要本月 26 日到 31 日之间的记录。

The monthly cycle is from 26 to 25 and the query is supposed to be executed every day.每月周期是从 26 到 25,查询应该每天执行一次。 I'm not able to figure out how to write a where clause for this.我无法弄清楚如何为此编写 where 子句。

this is the structure of the table that I have:这是我拥有的表的结构:

order_id    order_date    bill
  1          2021-02-25    500
  2          2021-02-25    1000
  3          2021-02-26    1500
  4          2021-02-27    150
  5          2021-02-28    25
  6          2021-03-02    78
              .
              .
              .
 4250        2021-03-25    500

The general format of the query might look like this:查询的一般格式可能如下所示:

select *
from t
where
day(curdate()) between 26 and 31) and order_date between a and b or
day(curdate()) not between 26 and 31) and order_date between c and d

or:或者:

select *
from t
where
order_date between if(curdate()) between 26 and 31, a, c) and if(curdate() between 26 and 31, b, d)

where a, b and c would use date calculations.其中 a、b 和 c 将使用日期计算。 For a it would be adddate(subdate(curdate(), interval day(curdate()) day), interval 26 day) .对于 a ,它将是adddate(subdate(curdate(), interval day(curdate()) day), interval 26 day) b would be last_day(curdate()) . b 将是last_day(curdate())

If you want to write a WHERE clause using the BETWEEN predicate, there is a way to use EXISTS (subquery) .如果要使用 BETWEEN 谓词编写 WHERE 子句,可以使用EXISTS (subquery)

SELECT * FROM mytable m
WHERE EXISTS
(SELECT 1 FROM (SELECT LAST_DAY(CURDATE() - INTERVAL 25 DAY) d) t
 WHERE m.order_date
    BETWEEN
        d + INTERVAL (-DAY(d)+1+25) DAY
        AND
        d + INTERVAL 25 DAY)

The extraction range is the period obtained by adding 25 to the 1st day and the last day of the month including the start date.提取范围是包括开始日期在内的当月的第一天和最后一天加上 25 得到的时间段。

LAST_DAY(CURDATE() - INTERVAL 25 DAY) always maps to the last day of the same month. LAST_DAY(CURDATE() - INTERVAL 25 DAY)始终映射到同一个月的最后一天。

2021-02-26 -> 2021-02-01 -> 2021-02-28
2021-02-27 -> 2021-02-02 -> 2021-02-28
2021-02-28 -> 2021-02-03 -> 2021-02-28
2021-03-01 -> 2021-02-04 -> 2021-02-28
:
2021-03-25 -> 2021-02-28 -> 2021-02-28

About d + INTERVAL (-DAY(d)+1+25) DAY , -DAY(d)+1 is the first day, so -DAY(d)+1+25 is 26th of that month.关于d + INTERVAL (-DAY(d)+1+25) DAY-DAY(d)+1是第一天,所以-DAY(d)+1+25是该月的第 26 天。 d + INTERVAL 25 DAY is 25th of that next month. d + INTERVAL 25 DAY是下个月的 25 日。

Fiddle小提琴

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

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