取消组一行到基于日期部分许多行(Un-group a row into many rows base

2019-10-17 13:42发布

我使用MySQL和我有一个Policy与表StartDateEndDate列。

我怎么能写一个SELECT查询给我每月一个新的行中这2列之间的时间范围。

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

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

Answer 1:

我不知道性能,因为我没有太多的存储过程经历了那么有可能是一个更好的办法。 此外,您可能要更改的临时表的结构(亦称PolicyList )。 无论如何…

这也可以被转化成前/触发器代替每次执行它的后。

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;


文章来源: Un-group a row into many rows based on date parts