1

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

如何编写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
4

1 回答 1

0

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

这也可以转换为之前/之后的触发器,而不是每次都执行。

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;
于 2013-01-11T21:55:08.373 回答