简体   繁体   English

是否有一种灵活的方法来指定日期范围?

[英]Is there a flexible way to specify ranges of dates?

I am working with MySQL.我正在使用 MySQL。

I have some queries that begin like this:我有一些这样开始的查询:

WITH dates (start_date, end_date) AS (
  SELECT '2020-11-01', '2020-11-02'
    UNION ALL SELECT '2020-11-02', '2020-11-03',
    UNION ALL SELECT '2020-11-03', '2020-11-04')
SELECT dates.start_date, dates.end_date, id, COUNT(*)
 FROM dates 
   INNER JOIN ...

I also sometimes need to run the same query, but with each date range being a week (Monday to Sunday), or a calendar month.我有时还需要运行相同的查询,但每个日期范围是一周(周一到周日)或日历月。 Moreover, sometimes there are 100 or more of these, which is quite prone to typos in addition to occupying a lot of lines and taking a long time to write.而且,这些有时有100个以上,除了占用很多行,需要很长时间编写之外,还很容易出现错别字。

Is there more elegant and flexible way to achieve this?有没有更优雅和灵活的方式来实现这一点? Ideally I would like to be able to just specify a overall start date, an overall end date and a period (daily, weekly, monthly, yearly etc)理想情况下,我希望能够仅指定总体开始日期、总体结束日期和期间(每天、每周、每月、每年等)

You can use a recursive CTE:您可以使用递归 CTE:

with recursive dates as (
      select date('2020-11-01') as start_date, date('2020-11-02') as end_date
      union all
      select start_date + interval 1 day, end_date + interval 1 day
      from dates
      where start_date < '2020-12-01'
     )
select *
from dates;

Here is a db<>fiddle. 是一个 db<>fiddle。 Of course, the logic would be a little different for months.当然,几个月后逻辑会有所不同。

  1. Create some date_ranges table which stores: series identifier, range number, range boundaries.创建一些date_ranges表,其中存储:系列标识符、范围号、范围边界。
  2. Insert needed series into it each time when you need a series which is not present in this table yet.每次需要此表中尚不存在的系列时,将所需系列插入其中。
  3. Use this table as source table in your query (maybe with additional condition which narrows the range if needed).将此表用作查询中的源表(如果需要,可能带有缩小范围的附加条件)。
  4. Remove series which will be used never in future.删除以后永远不会使用的系列。

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

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