4. WITH last_touch AS (
SELECT user_id,
MAX(timestamp) as last_touch_at
FROM page_visits
GROUP BY user_id),
lt_utm AS (
SELECT lt.user_id,
lt.last_touch_at,
pv.utm_source,
pv.utm_campaign
FROM last_touch AS 'lt'
JOIN page_visits AS 'pv'
ON lt.user_id = pv.user_id
AND lt.last_touch_at = pv.timestamp)
SELECT COUNT(*),lt_utm.utm_campaign,
lt_utm.utm_source
FROM lt_utm
GROUP BY 2
ORDER BY 1 DESC;
This is an excellent query that pulls together all the data we need in order to answer the question. I just wanted to point out that we can GROUP BY on both lt_utm.utm_campaign and lt_utm.utm_source for this query. So, we can change our GROUP BY clause to be:
GROUP BY 2, 3
Although this won't change the results of our output, it may clean up how the table is presented to us. But, this is just a note! The query is perfectly acceptable as it is.
This is an excellent query that pulls together all the data we need in order to answer the question. I just wanted to point out that we can
GROUP BYon bothlt_utm.utm_campaignandlt_utm.utm_sourcefor this query. So, we can change ourGROUP BYclause to be:GROUP BY 2, 3Although this won't change the results of our output, it may clean up how the table is presented to us. But, this is just a note! The query is perfectly acceptable as it is.