forked from dbt-labs/snowplow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpg_udfs.sql
67 lines (55 loc) · 1.65 KB
/
pg_udfs.sql
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
-- convert_timezone
create function convert_timezone(
in_tzname text,
out_tzname text,
in_t timestamptz
) returns timestamptz
as $$
declare
begin
return in_t at time zone out_tzname at time zone in_tzname;
end;
$$ language plpgsql;
-- datediff
create or replace function datediff(
units varchar(30),
start_t timestamp,
end_t timestamp) returns int
as $$
declare
diff_interval interval;
diff int = 0;
years_diff int = 0;
begin
if units in ('yy', 'yyyy', 'year', 'mm', 'm', 'month') then
years_diff = date_part('year', end_t) - date_part('year', start_t);
if units in ('yy', 'yyyy', 'year') then
-- sql server does not count full years passed (only difference between year parts)
return years_diff;
else
-- if end month is less than start month it will subtracted
return years_diff * 12 + (date_part('month', end_t) - date_part('month', start_t));
end if;
end if;
-- Minus operator returns interval 'DDD days HH:MI:SS'
diff_interval = end_t - start_t;
diff = diff + date_part('day', diff_interval);
if units in ('wk', 'ww', 'week') then
diff = diff/7;
return diff;
end if;
if units in ('dd', 'd', 'day') then
return diff;
end if;
diff = diff * 24 + date_part('hour', diff_interval);
if units in ('hh', 'hour') then
return diff;
end if;
diff = diff * 60 + date_part('minute', diff_interval);
if units in ('mi', 'n', 'minute') then
return diff;
end if;
diff = diff * 60 + date_part('second', diff_interval);
return diff;
end;
$$ language plpgsql;