简体   繁体   中英

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

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. But with STR_TO_DATE you can solve this. the date Problems as you can see keeps bugging mysql. The WHERE clause uses BETWEEN to select the wanted date frame this has to be in the right date format. Of course you have to adept it to your tablebane and columnname

DBfiddle Example

First, fix the data so it uses date , the proper format for storing a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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