gpt4 book ai didi

mysql - 根据日期部分将一行取消分组为多行

转载 作者:行者123 更新时间:2023-11-30 23:23:53 26 4
gpt4 key购买 nike

我正在使用 MySql,我有一个包含 StartDateEndDate 列的 Policy 表。

我如何编写一个 SELECT 查询来为这两列之间的日期范围内的每个月提供一个新行。

例如,如果我有一个政策:

Id        StartDate        EndDate
123456 2011-05-25 2011-07-26

我想看看:

Id       PolicyId        StartDate        EndDate
1 123456 2011-05-25 2011-06-24
2 123456 2011-06-25 2011-07-24
3 123456 2011-07-25 2011-07-26

最佳答案

我不确定性能,因为我对存储过程的经验不多,所以可能有更好的方法。此外,您可能想要更改临时表的结构(又名。PolicyList)。不管怎样……

这也可以转化为before/after触发器,而不是每次都执行。

DROP PROCEDURE IF EXISTS CreatePolicyList;

DELIMITER //
CREATE PROCEDURE CreatePolicyList()
BEGIN
DECLARE origId, done INT DEFAULT 0;
DECLARE startD, endD DATE;

DECLARE cur CURSOR FOR
SELECT id, StartDate, EndDate FROM Policy;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

DROP TEMPORARY TABLE IF EXISTS PolicyList;
CREATE TEMPORARY TABLE PolicyList (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
PolicyId INT(11) NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

OPEN cur;
recLoop: LOOP
FETCH cur INTO origId, startD, endD;
IF (done)
THEN LEAVE recLoop;
END IF;

-- following is an alternative to keep records like
-- "2011-05-25, 2011-06-25" in a single record
-- WHILE startD < DATE_SUB(endD, INTERVAL 1 MONTH) DO
WHILE startD < DATE_ADD(DATE_SUB(endD, INTERVAL 1 MONTH), INTERVAL 1 DAY) DO
INSERT INTO PolicyList (PolicyId, StartDate, EndDate)
VALUES (origId, startD,DATE_SUB(
DATE_ADD(startD, INTERVAL 1 MONTH),
INTERVAL 1 DAY
));
SET startD = DATE_ADD(startD, INTERVAL 1 MONTH);
END WHILE;

IF startD >= DATE_SUB(endD, INTERVAL 1 MONTH) THEN
INSERT INTO PolicyList (PolicyId, StartDate, EndDate)
VALUES (origId, startD, endD);
END IF;
END LOOP;
CLOSE cur;

END //

CALL CreatePolicyList;

然后查询:

SELECT * FROM PolicyList
ORDER BY PolicyId, StartDate;

关于mysql - 根据日期部分将一行取消分组为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14277964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com