A company is running ads and wants to calculate the performance of each ad using Click-Through Rate (CTR).
The Ads table contains:
ad_id- ID of the advertisementuser_id- ID of the user who interacted with the adaction- User action: 'Clicked', 'Viewed', or 'Ignored'
Click-Through Rate (CTR) is calculated as:
CTR = (Number of Clicks) / (Number of Clicks + Number of Views) × 100
Write a SQL query to find the CTR of each ad. Round CTR to two decimal places. Return results ordered by CTR in descending order, and by ad_id in ascending order for ties.
Note: If an ad has no clicks or views, it should not appear in the result.
Table Schema
| Column Name | Type | Description |
|---|---|---|
ad_id
PK
|
int | Advertisement ID |
user_id
PK
|
int | User ID who performed the action |
action
|
enum | Action taken: 'Clicked', 'Viewed', or 'Ignored' |
Input & Output
| ad_id | user_id | action |
|---|---|---|
| 1 | 1 | Clicked |
| 1 | 2 | Viewed |
| 1 | 3 | Ignored |
| 2 | 1 | Viewed |
| 2 | 3 | Ignored |
| 3 | 1 | Clicked |
| 3 | 2 | Clicked |
| ad_id | ctr |
|---|---|
| 3 | 100 |
| 1 | 50 |
| 2 | 0 |
Ad 1: 1 click + 1 view = CTR of (1/2) × 100 = 50.00%
Ad 2: 0 clicks + 1 view = CTR of (0/1) × 100 = 0.00%
Ad 3: 2 clicks + 0 views = CTR of (2/2) × 100 = 100.00%
Results ordered by CTR descending: Ad 3 (100.00), Ad 1 (50.00), Ad 2 (0.00)
| ad_id | user_id | action |
|---|---|---|
| 1 | 1 | Ignored |
| 1 | 2 | Ignored |
| 2 | 1 | Clicked |
| 2 | 2 | Viewed |
| ad_id | ctr |
|---|---|
| 2 | 50 |
Ad 1: Only ignored actions, so it doesn't appear in results (no clicks or views)
Ad 2: 1 click + 1 view = CTR of (1/2) × 100 = 50.00%
Only ads with clicks or views are included in the output.
Constraints
-
1 ≤ ad_id, user_id ≤ 100 -
actionis an enum of('Clicked', 'Viewed', 'Ignored') -
The number of rows in the table is between
1and100