Problem
Table: Ads
|
|
A company is running Ads and wants to calculate the performance of each Ad.
Performance of the Ad is measured using Click-Through Rate (CTR) where:
$$ CTR = \begin{cases} 0 & \text{if Ad total clicks + Ad total views = 0} \\ \frac{\text{Ad total clicks}}{\text{Ad total clicks + Ad total views}} x 100 & \text{, otherwise} x < 0 \end{cases} $$
Write a solution to find the ctr
of each Ad. Round ctr
to two decimal points.
Return the result table ordered by ctr
in descending order and by ad_id
in ascending order in case of a tie.
The result format is in the following example.
Examples
Example 1
|
|
Solution
Method 1 – Using Conditional Aggregation
Intuition
We need to calculate the Click-Through Rate (CTR) for each ad. The CTR is the percentage of clicks out of the total number of clicks and views for each ad. We ignore “Ignored” actions. By grouping by ad_id
and using conditional aggregation, we can count clicks and views efficiently.
Approach
- Group by
ad_id
: Aggregate data for each ad. - Count Clicks and Views: Use
SUM(CASE WHEN ...)
to count “Clicked” and “Viewed” actions separately. - Calculate CTR:
- If total clicks + views is 0, CTR is 0.
- Otherwise, CTR = (clicks / (clicks + views)) * 100.
- Round CTR: Use
ROUND(..., 2)
to round to two decimal places. - Order Results: Sort by
ctr
descending, then byad_id
ascending.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
— Each row is scanned once for aggregation. - 🧺 Space complexity:
O(k)
— Wherek
is the number of uniquead_id
values.