简体   繁体   English

mysql中多个日期范围内的月份列表

[英]List of months within multiple date ranges in mysql

I have a list of date ranges and I like to get a list of all months that are within these date ranges. 我有一个日期范围列表,我想获得这些日期范围内所有月份的列表。 I can query my date ranges like so: 我可以这样查询日期范围:

Select id, start, end 
From date_range

And this query would give the following output: 并且此查询将给出以下输出:

1, 01-01-2016, 25-03-2016
2, 26-03-2016, 30-03-2016
3, 30-12-2016, 08-01-2017

Now I would like to find a MySQL query that just lists all months within these date ranges. 现在,我想找到一个MySQL查询,该查询只列出这些日期范围内的所有月份。 So it should give the following output: 因此,它应提供以下输出:

01-2016
02-2016
03-2016
12-2016
01-2017

There are already examples here on how to get a list of month between two dates, such as: 此处已经有有关如何获取两个日期之间的月份列表的示例,例如:

But these examples are about a single date range, but I have multiple date ranges. 但是这些示例仅涉及一个日期范围,但是我有多个日期范围。 It would be great if someone can find an sql query for my problem. 如果有人可以找到我的问题的SQL查询,那将是很好。

Here is a solution: 这是一个解决方案:

#DROP TABLE IF EXISTS monthTest;
CREATE TABLE monthTest(id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, `start` DATETIME, `end`DATETIME);

INSERT INTO monthTest(`start`, `end`) VALUES
    ('2016-01-01', '2016-03-25'),
    ('2016-03-26', '2016-03-30'),
    ('2016-12-30', '2017-08-01');

SELECT A.`start`, A.`end`, DATE_FORMAT(DATE_ADD(A.`start`, INTERVAL B.help_keyword_id MONTH), '%Y%m') FROM
    monthTest A,
    mysql.help_keyword B
WHERE PERIOD_DIFF(DATE_FORMAT(A.`end`, '%Y%m'), DATE_FORMAT(A.`start`, '%Y%m')) >= B.help_keyword_id
ORDER BY A.id;

Note that this query in the second JOIN table has a dependency that this table must contain more rows than the maximum number of months between any two dates and the join field must be an incrementing INTEGER starting from 0. This is due to the limitation that mysql doesn't (yet) contain a row generator so a workaround is necessary. 请注意,第二个JOIN表中的该查询具有以下依赖性:该表必须包含比任何两个日期之间的最大月份数更多的行,并且join字段必须是从0开始的递增INTEGER 。这是由于mysql的限制(尚未)包含行生成器,因此需要变通方法。

Regards, 问候,

James 詹姆士

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

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