Skip to content

Commit 5791ce0

Browse files
authored
fix: user acquisition first user with last non direct source (#44)
1 parent 5f24bf5 commit 5791ce0

File tree

1 file changed

+42
-14
lines changed

1 file changed

+42
-14
lines changed

models/50_intermediate/segment/int_segment__sessions_first_touch_point.sql

Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,59 @@
11
{{ config(materialized="incremental", unique_key="canonical_segment_id") }}
22

33
with
4-
first_touch_anonymous as (
4+
all_sessions as (
55
select
66
anonymous_id,
77
canonical_segment_id_with_fallback as canonical_segment_id,
8-
min(session_start_tstamp) as record_timestamp
8+
referrer_source as src,
9+
referrer_medium as med,
10+
referrer_id as id,
11+
session_start_tstamp as ts
912
from {{ ref("int_segment__sessions") }}
13+
),
14+
15+
agg as (
16+
select
17+
canonical_segment_id,
18+
anonymous_id,
19+
array_agg(struct(src, med, id, ts) order by ts) as all_touches,
20+
array_agg(
21+
if(
22+
src in ('direct', 'session_continue'),
23+
null,
24+
struct(src, med, id, ts)
25+
)
26+
ignore nulls
27+
order by ts
28+
) as non_direct_touches
29+
from all_sessions
1030
group by 1, 2
1131
),
1232

1333
first_touch_canonical as (
1434
select
15-
fa.anonymous_id,
16-
fa.canonical_segment_id,
17-
fa.record_timestamp,
18-
s.referrer_id,
19-
s.referrer_source,
20-
s.referrer_medium
21-
from first_touch_anonymous as fa
22-
left join
23-
{{ ref("int_segment__sessions") }} as s
24-
on fa.anonymous_id = s.anonymous_id
25-
and fa.record_timestamp = s.session_start_tstamp
35+
canonical_segment_id,
36+
anonymous_id,
37+
coalesce(
38+
(non_direct_touches[safe_offset(0)]).src,
39+
(all_touches[safe_offset(0)]).src
40+
) as referrer_source,
41+
coalesce(
42+
(non_direct_touches[safe_offset(0)]).med,
43+
(all_touches[safe_offset(0)]).med
44+
) as referrer_medium,
45+
coalesce(
46+
(non_direct_touches[safe_offset(0)]).id,
47+
(all_touches[safe_offset(0)]).id
48+
) as referrer_id,
49+
coalesce(
50+
(non_direct_touches[safe_offset(0)]).ts,
51+
(all_touches[safe_offset(0)]).ts
52+
) as record_timestamp
53+
from agg
2654
qualify
2755
row_number() over (
28-
partition by fa.canonical_segment_id order by fa.record_timestamp asc
56+
partition by canonical_segment_id order by record_timestamp asc
2957
)
3058
= 1
3159
)

0 commit comments

Comments
 (0)