首页 > 解决方案 > 如何生成 MySQL 过程以获取日期范围内的日期,该日期范围增加 1 个月,直到结束日期

问题描述

我有一个包含一些数据的连接表,包括p_id,starts_onends_on. 我想增加starts_on1 个月,直到ends_on每个p_id.

所以,我的桌子看起来像;

p_id    starts_on    ends_on
-----------------------------
1      2018-01-01   2018-12-31
2      2018-05-03   2018-12-31
3      2018-06-01   2018-07-30

我想做的事情是这样的;

p_id    starts_on    ends_on
-----------------------------
1      2018-01-01   2018-12-31
1      2018-02-01   2018-12-31
1      2018-03-01   2018-12-31
.       .            .
.       .            .
1      2018-11-01   2018-12-31
1      2018-12-01   2018-12-31
2      2018-05-03   2018-12-31
2      2018-06-03   2018-12-31
.       .            .
.       .            .
2      2018-12-03   2018-12-31
3      2018-06-01   2018-07-30

等等。

那么,有什么办法可以做到吗?我查找只是增加日期,但我也需要根据 p_id 增加它

标签: mysql

解决方案


您可以为此使用光标:

create procedure sp_pids_expand()
begin
declare done int default 0;
declare v_p_id int;
declare v_starts_on date;
declare v_ends_on date;
declare v_newday date;
declare v_cnt int;

declare c_pids cursor for
  select p_id, starts_on, ends_on
  from pids
  where date_add(starts_on, interval 1 month)<ends_on;

declare continue handler for not found set done = 1;

open c_pids;
repeat
  fetch c_pids into v_p_id, v_starts_on, v_ends_on;

  if not done then
    set v_newday = v_starts_on;
    while (date_add(v_newday, interval 1 month)<v_ends_on) do

      set v_newday = date_add(v_newday, interval 1 month);

      select count(*) into v_cnt
      from pids
      where p_id=v_p_id and starts_on=v_newday and ends_on=v_ends_on;

      if (v_cnt=0) then
        insert into pids (p_id, starts_on, ends_on)
        values (v_p_id, v_newday, v_ends_on);
      end if;      
    end while;

  end if;
until done end repeat;

close c_pids;

end

推荐阅读