Skip to content

Instantly share code, notes, and snippets.

@nickpad
Last active February 26, 2017 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickpad/9852938c330cd41930403f7905d369ac to your computer and use it in GitHub Desktop.
Save nickpad/9852938c330cd41930403f7905d369ac to your computer and use it in GitHub Desktop.
-- Construct an account to anonymous ID mapping
with account_mappings as (
select distinct on (anonymous_id)
anonymous_id,
account_id
from app_production.identifies
where anonymous_id is not null
order by anonymous_id, account_id
),
-- Get the time that each account first subscribed
sign_ups as (
select id as account_id, name, email, created_at from production.accounts
)
-- Get the first and last click id from the set of clicks before sign up
select distinct on (account_id)
ad_clicks.anonymous_id,
first_value(ad_clicks.id) over browser_clicks as first_click_id,
last_value(ad_clicks.id) over browser_clicks as last_click_id,
sign_ups.account_id,
coalesce(sign_ups.name, sign_ups.email) as name,
sign_ups.created_at as signed_up_at
from derived.ad_clicks
inner join account_mappings on account_mappings.anonymous_id = ad_clicks.anonymous_id
inner join sign_ups on sign_ups.account_id = account_mappings.account_id
where
ad_clicks.received_at between
(sign_ups.created_at - interval '21 days') and sign_ups.created_at
window browser_clicks as (partition by account_mappings.account_id order by ad_clicks.received_at)
order by account_id, ad_clicks.received_at desc
with pages_with_ad_ids as (
select
id,
anonymous_id,
received_at,
substring(search, '.*[?&]gclid=([^$&]*)') as gcl_id,
substring(search, '.*[?&]fbad_id=([^$&]*)') as fbad_id
from marketing.pages
)
select
p.id,
p.received_at,
p.anonymous_id,
case
when p.gcl_id is not null and p.fbad_id is null then 'Google'
when p.fbad_id is not null and p.gcl_id is null then 'Facebook'
else 'wtf'
end as platform,
case
when p.gcl_id is not null then coalesce(g3.name, '[unknown]')
when p.fbad_id is not null then coalesce(f3.name, '[unknown]')
else 'wtf'
end as campaign_name,
case
when p.gcl_id is not null then coalesce(g2.name, '[unknown]')
when p.fbad_id is not null then coalesce(f2.name, '[unknown]')
else 'wtf'
end as ad_group_name
from pages_with_ad_ids p
left join adwords.click_performance_reports g1 on g1.gcl_id = p.gcl_id
left join adwords.ad_groups g2 on g2.id = g1.ad_group_id
left join adwords.campaigns g3 on g3.id = g2.campaign_id
left join facebookads.ads f1 on f1.id = p.fbad_id
left join facebookads.ad_sets f2 on f2.id = f1.adset_id
left join facebookads.campaigns f3 on f3.id = f2.campaign_id
where p.gcl_id is not null or p.fbad_id is not null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment