简体   繁体   English

获取给定日期范围内的连续月份

[英]Get the consecutive months for a given date range

In my table I have dates as follows 在我的桌子上,我的日期如下

08/08/2011
29/08/2011
30/08/2011
31/08/2011
12/09/2011
13/09/2011
23/10/2011
24/10/2011
25/10/2011
26/10/2011

Now I need the records to be displayed based on a given date range eg: if from date is 8/08/2011 and to date is 20/10/2011 then the data should come as below 现在我需要根据给定日期范围如要显示的记录:如果从日期是8/08/2011和日期是20/10/2011 ,则数据应是如下

29/08/2011   Aug
30/08/2011   Aug
31/08/2011   Aug
12/09/2011   Sept
13/09/2011   Sept

BAsed on the data you provided 根据您提供的数据

CREATE TABLE notes
(`datecreated` varchar(10))
;

INSERT INTO notes
  (`datecreated`)
VALUES
  ('08/08/2011'),
  ('29/08/2011'),
  ('30/08/2011'),
  ('31/08/2011'),
  ('12/09/2011'),
  ('13/09/2011'),
  ('23/10/2011'),
  ('24/10/2011'),
  ('25/10/2011'),
  ('26/10/2011')
  ;

You can use 您可以使用

 Select 
   STR_TO_DATE(datecreated, '%d/%c/%Y') datecreated 
   , DATE_FORMAT(STR_TO_DATE(datecreated, '%d/%c/%Y'),'%b') monthname
 From notes
 WHERE 
   STR_TO_DATE(datecreated, '%d/%c/%Y') BETWEEN '2011-08-29' AND '2011-09-13';

the result is 结果是

datecreated     monthname
2011-08-29      Aug
2011-08-30      Aug
2011-08-31      Aug
2011-09-12      Sep
2011-09-13      Sep

The biggest Problem is that your date is not in a Format that mysql can import. 最大的问题是您的日期不是mysql可以导入的格式。 But with STR_TO_DATE you can solve this. 但是使用STR_TO_DATE,您可以解决此问题。 the date Problems as you can see keeps bugging mysql. 日期,如您所见,问题一直困扰着mysql。 The WHERE clause uses BETWEEN to select the wanted date frame this has to be in the right date format. WHERE子句使用BETWEEN选择所需的日期框架,该日期框架必须采用正确的日期格式。 Of course you have to adept it to your tablebane and columnname 当然,您必须将其适应于您的表格和列名

DBfiddle Example DBfiddle示例

First, fix the data so it uses date , the proper format for storing a date: 首先,修复数据,使其使用date来存储日期的正确格式:

update notes
    set datecreated = str_to_date(datecreated, '%d/%m/%Y');

alter table notes modify column datecreated date;

select *
from notes;

Then, if you want to sort the data, just use: 然后,如果要对数据进行排序,请使用:

order by datecreated;

If you want your exact result set: 如果您想要确切的结果集:

select datecreated, left(monthname(datecreated), 3)
from notes
where datecreated < '2011-10-01'
order by datecreated;

Here is a db<>fiddle. 是db <>小提琴。

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

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