Skip to content
Advertisement

BigQuery – How to select the first campaign each user clicked on?

Let’s imagine that I have a website that sells electronics. In order to attract customers, I invested some money in online ad campaigns.

The following table has three columns: user_id (id that identifies each user), event_date (the date when the user clicked on the ad) and mkt campaign (the name of the ad campaign):

I want to select only the rows that contain the first campaign that attracted each user to my website. In other words, I need to identify how each user got to my website for the first time.

The expected result would be like this:

I know that I could use “ORDER BY event_date ASC” to order the rows by date. However, I need the result to show only one result per user_id (the one with the oldest campaign).

Please, do you know how to do this in BigQuery (BQ Standard SQL)?

Thank you very much.

Advertisement

Answer

Consider below approach

if apply to sample data in your question as

output is

enter image description here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement