Join ML Engineer Interview MasterClass (April Cohort) led by FAANG Data Scientists | Just 6 seats remaining...
ML Engineer MasterClass (April) | 6 seats left
By the end of this lesson, you will:
Your manager at Google Ads, Jordan, wants to analyze how different campaigns from the same company compare to each other.
Can you list all campaign pairs within each company so we can compare their performance?
Your task is to use a SELF JOIN to find all campaign comparisons for the same advertiser.
| campaign_id | user_id | campaign_name | ad_type | start_date | end_date | budget | impressions | clicks | conversions |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 1 | Growth Hackers Special | Search | 2024-01-10T00:00:00 | 2024-02-10T00:00:00 | 5000 | 500000 | 12000 | 800 |
| 2 | 2 | BigTech Awareness | Display | 2024-01-05T00:00:00 | 2024-02-20T00:00:00 | 20000 | 2000000 | 50000 | 3000 |
| 3 | 3 | Ecom Holiday Sales | Shopping | 2023-11-15T00:00:00 | 2024-01-15T00:00:00 | 10000 | 750000 | 22000 | 1500 |
| 4 | 4 | Fashion Hub Summer | Video | 2024-02-01T00:00:00 | 2024-03-01T00:00:00 | 15000 | 900000 | 18000 | 1200 |
| 5 | 5 | HealthyLife Brand Push | Search | 2024-01-20T00:00:00 | 2024-03-10T00:00:00 | 8000 | 600000 | 15000 | 900 |
A SELF JOIN joins a table to itself by treating it as if it were two separate tables.
| Why use SELF JOIN? |
|---|
| Compare records within the same table |
| Find relationships between different rows in the same dataset |
| Analyze hierarchical or grouped data |
1SELECT a.column1, b.column2
2FROM table_name a
3JOIN table_name b
4ON a.common_key = b.common_key;a, b) to the table so it can be referenced twice.ON to define the relationship between the two rows.Jordan wants to see all campaign comparisons within each company.
1SELECT a.company, a.campaign_name AS campaign_1, b.campaign_name AS campaign_2
2FROM google_ads_campaigns a
3JOIN google_ads_campaigns b
4ON a.company = b.company
5AND a.campaign_id < b.campaign_id;| company | campaign_1 | campaign_2 |
|---|---|---|
| BigTech Corp | BigTech Awareness | Product Launch 2024 |
| FashionHub | Fashion Hub Summer | New Collection Ads |
| EcomStore | Ecom Holiday Sales | Black Friday Special |
What’s Happening?
SELF JOIN finds pairs of campaigns within the same company.a.campaign_id < b.campaign_id ensures each pair appears only once (avoids duplicates).Jordan wants to compare all campaign pairs for each company.
Filter condition:
company in ascending order.| company | campaign_1 | campaign_2 |
|---|---|---|
| BigTech Corp | BigTech Awareness | Product Launch 2024 |
| FashionHub | Fashion Hub Summer | New Collection Ads |
| EcomStore | Ecom Holiday Sales | Black Friday Special |
Write an SQL query to return the requested data.