forked from dbt-labs/dbt-utils
-
Notifications
You must be signed in to change notification settings - Fork 2
/
generate_series.sql
45 lines (31 loc) · 936 Bytes
/
generate_series.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
{% macro get_powers_of_two(upper_bound) %}
{% if upper_bound <= 0 %}
{{ exceptions.raise_compiler_error("upper bound must be positive") }}
{% endif %}
{% for _ in range(1, 100) %}
{% if upper_bound <= 2 ** loop.index %}{{ return(loop.index) }}{% endif %}
{% endfor %}
{% endmacro %}
{% macro generate_series(upper_bound) %}
{% set n = dbt_utils.get_powers_of_two(upper_bound) %}
with p as (
select 0 as generated_number union all select 1
), unioned as (
select
{% for i in range(n) %}
p{{i}}.generated_number * pow(2, {{i}})
{% if not loop.last %} + {% endif %}
{% endfor %}
+ 1
as generated_number
from
{% for i in range(n) %}
p as p{{i}}
{% if not loop.last %} cross join {% endif %}
{% endfor %}
)
select *
from unioned
where generated_number <= {{upper_bound}}
order by generated_number
{% endmacro %}