forked from bakineggs/recurring_events_for
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintervals_between.sql
More file actions
29 lines (29 loc) · 793 Bytes
/
Copy pathintervals_between.sql
File metadata and controls
29 lines (29 loc) · 793 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
CREATE OR REPLACE FUNCTION intervals_between(
start_date DATE,
end_date DATE,
duration INTERVAL
)
RETURNS FLOAT
LANGUAGE plpgsql IMMUTABLE
AS $BODY$
DECLARE
count FLOAT := 0;
multiplier INT := 512;
BEGIN
IF start_date > end_date THEN
RETURN 0;
END IF;
WHILE start_date + multiplier * duration < end_date LOOP
multiplier := multiplier * 2;
END LOOP;
LOOP
IF start_date + (count + multiplier) * duration < end_date THEN
count := count + multiplier;
END IF;
EXIT WHEN multiplier = 1;
multiplier := multiplier / 2;
END LOOP;
count := count + (extract(epoch from end_date) - extract(epoch from (start_date + count * duration))) / (extract(epoch from end_date + duration) - extract(epoch from end_date))::int;
RETURN count;
END
$BODY$;