Last active
August 29, 2015 14:24
-
-
Save ststeiger/0fee7d5fc1ea8540f32b to your computer and use it in GitHub Desktop.
PostGre: Calculate number of overlapping days in two date ranges
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| DROP FUNCTION IF EXISTS fn_OverlappingDateRangesDays( | |
| __firstStart timestamp without time zone | |
| ,__firstEnd timestamp without time zone | |
| ,__secondStart timestamp without time zone | |
| ,__secondEnd timestamp without time zone); | |
| CREATE OR REPLACE FUNCTION fn_OverlappingDateRangesDays( | |
| __firstStart timestamp without time zone | |
| ,__firstEnd timestamp without time zone | |
| ,__secondStart timestamp without time zone | |
| ,__secondEnd timestamp without time zone | |
| ) | |
| RETURNS integer | |
| AS $$ | |
| DECLARE | |
| __maxStart timestamp without time zone; | |
| __minEnd timestamp without time zone; | |
| __interval int; | |
| BEGIN | |
| IF __firstStart IS NULL OR __firstEnd IS NULL OR __secondStart IS NULL OR __secondEnd IS NULL THEN | |
| -- RETURN 0 | |
| RETURN NULL; | |
| END IF; | |
| IF __firstEnd < __firstStart THEN | |
| RETURN 0; | |
| END IF; | |
| IF __secondEnd < __secondStart THEN | |
| RETURN 0; | |
| END IF; | |
| __maxStart := __secondStart; | |
| __minEnd := __secondEnd; | |
| IF __firstStart > __secondStart THEN | |
| __maxStart := __firstStart; | |
| END IF; | |
| IF __firstEnd < __secondEnd THEN | |
| __minEnd := __firstEnd ; | |
| END IF; | |
| -- PRINT __maxStart | |
| -- PRINT __minEnd | |
| -- __interval := DATEDIFF(DAY, __maxStart, __minEnd) + 1; | |
| -- __interval := {fn timestampdiff(SQL_TSI_DAY, __maxStart, __minEnd)} + 1; | |
| __interval := EXTRACT(day from __minEnd - __maxStart) + 1; | |
| IF __interval < 0 THEN | |
| __interval := 0; | |
| END IF; | |
| -- PRINT __interval | |
| RETURN __interval; | |
| END; | |
| $$ LANGUAGE plpgsql STRICT; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment