mysql - 如何生成 MySQL 过程以获取日期范围内的日期,该日期范围增加 1 个月,直到结束日期
问题描述
我有一个包含一些数据的连接表,包括p_id
,starts_on
和ends_on
. 我想增加starts_on
1 个月,直到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 增加它
解决方案
您可以为此使用光标:
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
推荐阅读
- influxdb - Telegraf 为我的时间戳添加随机 +1 到 +10 纳秒
- sql - 在 SQL Server 中以动态范围显示计数
- c# - 如何将字符串转换为数组并对其进行解码
- openid-connect - SAML 2.0 到 OpenID Connect 缺少 SUB 声明
- typescript - 如何声明具有与枚举相同键的泛型类型?
- mysql - 在 laravel 中将数据从外键添加到数据库中
- javascript - 什么时候承诺不再被优先考虑?
- java - java - 如何在java eclipse中绘制paintComponent背景而不与其他图像重叠?
- excel - 如何从excel中的固定值中减去新值?
- sql - 使用 SQL 服务器进行空间(距离)平均