Comparing date ranges

后端 未结 10 1354
予麋鹿
予麋鹿 2020-11-22 16:10

In MySQL, If I have a list of date ranges (range-start and range-end). e.g.

10/06/1983 to 14/06/1983
15/07/1983 to 16/07/1983
18/07/1983 to 18/07/1983


        
相关标签:
10条回答
  • 2020-11-22 16:27

    In your expected results you say

    06/06/1983 to 18/06/1983 = IN LIST

    However, this period does not contain nor is contained by any of the periods in your table (not list!) of periods. It does, however, overlap the period 10/06/1983 to 14/06/1983.

    You may find the Snodgrass book (http://www.cs.arizona.edu/people/rts/tdbbook.pdf) useful: it pre-dates mysql but the concept of time hasn't changed ;-)

    0 讨论(0)
  • 2020-11-22 16:28

    I created function to deal with this problem in MySQL. Just convert the dates to seconds before use.

    DELIMITER ;;
    
    CREATE FUNCTION overlap_interval(x INT,y INT,a INT,b INT)
    RETURNS INTEGER DETERMINISTIC
    BEGIN
    DECLARE
        overlap_amount INTEGER;
        IF (((x <= a) AND (a < y)) OR ((x < b) AND (b <= y)) OR (a < x AND y < b)) THEN
            IF (x < a) THEN
                IF (y < b) THEN
                    SET overlap_amount = y - a;
                ELSE
                    SET overlap_amount = b - a;
                END IF;
            ELSE
                IF (y < b) THEN
                    SET overlap_amount = y - x;
                ELSE
                    SET overlap_amount = b - x;
                END IF;
            END IF;
        ELSE
            SET overlap_amount = 0;
        END IF;
        RETURN overlap_amount;
    END ;;
    
    DELIMITER ;
    
    0 讨论(0)
  • 2020-11-22 16:28

    Look into the following example. It will helpful for you.

        SELECT  DISTINCT RelatedTo,CAST(NotificationContent as nvarchar(max)) as NotificationContent,
                    ID,
                    Url,
                    NotificationPrefix,
                    NotificationDate
                    FROM NotificationMaster as nfm
                    inner join NotificationSettingsSubscriptionLog as nfl on nfm.NotificationDate between nfl.LastSubscribedDate and isnull(nfl.LastUnSubscribedDate,GETDATE())
      where ID not in(SELECT NotificationID from removednotificationsmaster where Userid=@userid) and  nfl.UserId = @userid and nfl.RelatedSettingColumn = RelatedTo
    
    0 讨论(0)
  • 2020-11-22 16:34

    If your RDBMS supports the OVERLAP() function then this becomes trivial -- no need for homegrown solutions. (In Oracle it apparantly works but is undocumented).

    0 讨论(0)
提交回复
热议问题