Un-group a row into many rows based on date parts

会有一股神秘感。 提交于 2019-12-24 10:49:33

问题


I'm using MySql and I have a Policy table with StartDate and EndDate columns.

How can I write a SELECT query to give me a new row for each month in the date range between these 2 columns.

For example if I have a policy with:

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

I would want to see:

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

回答1:


I'm not sure about performance because I'm not much experienced with stored procedures so there might be a better approach. Also, you might want to change the structure of the temporary table (aka. PolicyList). Anyway…

This can also be converted into before/after triggers instead of executing it each time.

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;

and then query:

SELECT * FROM PolicyList
ORDER BY PolicyId, StartDate;


来源:https://stackoverflow.com/questions/14277964/un-group-a-row-into-many-rows-based-on-date-parts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!