我想在mysql中获取两个日期之间的月份列表.
For Example:My Input is
From date 23-01-2013
To Date 01-04-2014
Output Should be
Jan 2013,
Feb 2013,
March 2013,
.
.
.
Jan 2014,
Feb 2014,
Mar 2014,
Apr 2014.
Run Code Online (Sandbox Code Playgroud)
val*_*lex 16
select
DATE_FORMAT(m1, '%b %Y')
from
(
select
('2013-01-23' - INTERVAL DAYOFMONTH('2013-01-23')-1 DAY)
+INTERVAL m MONTH as m1
from
(
select @rownum:=@rownum+1 as m from
(select 1 union select 2 union select 3 union select 4) t1,
(select 1 union select 2 union select 3 union select 4) t2,
(select 1 union select 2 union select 3 union select 4) t3,
(select 1 union select 2 union select 3 union select 4) t4,
(select @rownum:=-1) t0
) d1
) d2
where m1<='2014-04-01'
order by m1
Run Code Online (Sandbox Code Playgroud)
这是一个实际的解决方案,如果您想那样看,它并不是那么“优雅”,但是它可以工作,并且只需几个参数就可以使其成为函数和/或存储过程...
首先,我们需要一个包含一些记录的表,任何表。我们将使用该表作为行号表。(在您要显示的相同月份中,您将需要尽可能多的行,拥有较大的表会更好)>>
SELECT CONCAT(table_schema, '.', table_name) as schema_table, table_rows
FROM information_schema.TABLES
order by 2 desc limit 0,100
Run Code Online (Sandbox Code Playgroud)
这将告诉您实例上具有最多记录的前100个表,在此示例中,我使用的是mysql.help表,默认情况下,它带有几千条记录,并且始终存在...
set @start_date = '2013-01-23';
set @end_date = '2014-04-01';
set @months = -1;
select DATE_FORMAT(date_range,'%M, %Y') AS result_date from (
select (date_add(@start_date, INTERVAL (@months := @months +1 ) month)) as date_range
from mysql.help_topic a limit 0,1000) a
where a.date_range between @start_date and last_day(@end_date);
Run Code Online (Sandbox Code Playgroud)
解释:
1.设置日期变量2.设置月份值(用于添加月份)3.为每行选择一个日期(我们在同一行中添加月份并增加月份变量)4.过滤范围之间的日期5.输出格式日期。
这是最终的输出>>
January, 2013
February, 2013
March, 2013
April, 2013
May, 2013
June, 2013
July, 2013
August, 2013
September, 2013
October, 2013
November, 2013
December, 2013
January, 2014
February, 2014
March, 2014
April, 2014
Run Code Online (Sandbox Code Playgroud)