Skip to content

Commit

Permalink
trino/snowflake works
Browse files Browse the repository at this point in the history
  • Loading branch information
mjirv committed Jul 18, 2022
1 parent 6116b18 commit 671d5ab
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
3 changes: 2 additions & 1 deletion integration_tests/seeds/raw_orders_simple.csv
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ id,customer_id,order_date,status
17,7,2018-01-18,completed
18,6,2018-01-20,completed
19,5,2018-01-22,returned
20,2,2018-01-23,completed
20,2,2018-01-23,completed
21,3,2018-01-24,returned
26 changes: 19 additions & 7 deletions macros/funnel.sql
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,24 @@
{% macro snowflake__funnel(steps, event_stream) %}
with event_stream as ( {% if not (event_stream|string|trim).startswith('select ') %} select * from {% endif %} {{ event_stream }} )

, steps as (
{% for step in steps %}
select
'{{ step.event_type }}' as event_type
, {{ loop.index }} as index
{% if not loop.last %}
union all
{% endif %}
{% endfor %}
)
, event_funnel as (
select event_type, count(*) unique_users
select event_type, count(distinct user_id) as unique_users
from event_stream
match_recognize(
partition by user_id
order by event_date
measures event_type as event_type
one row per match
pattern({% for step in steps %} step_{{ loop.index }} {% endfor %} )
all rows per match
pattern({% for step in steps %} ({% for i in range(loop.length - loop.index + 1) %} step_{{ loop.index }}+{% endfor %}) {% if not loop.last %} | {% endif %} {% endfor %} )
define
{% for step in steps %}
step_{{ loop.index }} as event_type = '{{ step.event_type }}' {% if not loop.last %} , {% endif %}
Expand All @@ -65,10 +74,13 @@
)

, final as (
select event_type
, unique_users, 1.0 * unique_users / nullif(first_value(unique_users) over(), 0) as pct_conversion
, 1.0 * unique_users / nullif(lag(unique_users) over(order by unique_users), 0) as pct_of_previous
select event_funnel.event_type
, unique_users, cast(unique_users as double) / nullif(first_value(unique_users) over(order by steps.index), 0) as pct_conversion
, 1.0 * cast(unique_users as double) / nullif(lag(unique_users) over(order by steps.index), 0) as pct_of_previous
from event_funnel
left join steps
on event_funnel.event_type = steps.event_type
order by steps.index
)

select * from final
Expand Down

0 comments on commit 671d5ab

Please sign in to comment.