题目描述

(通过次数8,846 | 提交次数14,870,通过率59.49%)

表: Ads
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| ad_id         | int     |
| user_id       | int     |
| action        | enum    |
+---------------+---------+
(ad_id, user_id) 是该表的主键
该表的每一行包含一条广告的 ID(ad_id),用户的 ID(user_id) 和用户对广告采取的行为 (action)
action 列是一个枚举类型 ('Clicked', 'Viewed', 'Ignored') 。

一家公司正在运营这些广告并想计算每条广告的效果。
广告效果用点击通过率(Click-Through Rate:CTR)来衡量,公式如下:
如果点击数+访问数为0,则返回0;否则,返回点击数*100/(点击数+访问数)。

写一条SQL语句来查询每一条广告的ctr,
ctr要保留两位小数。结果需要按ctr降序、按ad_id升序进行排序。
查询结果示例如下:
Ads 表:
+-------+---------+---------+
| ad_id | user_id | action  |
+-------+---------+---------+
| 1     | 1       | Clicked |
| 2     | 2       | Clicked |
| 3     | 3       | Viewed  |
| 5     | 5       | Ignored |
| 1     | 7       | Ignored |
| 2     | 7       | Viewed  |
| 3     | 5       | Clicked |
| 1     | 4       | Viewed  |
| 2     | 11      | Viewed  |
| 1     | 2       | Clicked |
+-------+---------+---------+
结果表:
+-------+-------+
| ad_id | ctr   |
+-------+-------+
| 1     | 66.67 |
| 3     | 50.00 |
| 2     | 33.33 |
| 5     | 0.00  |
+-------+-------+
对于 ad_id = 1, ctr = (2/(2+1)) * 100 = 66.67
对于 ad_id = 2, ctr = (1/(1+2)) * 100 = 33.33
对于 ad_id = 3, ctr = (1/(1+1)) * 100 = 50.00
对于 ad_id = 5, ctr = 0.00, 注意 ad_id = 5 没有被点击 (Clicked) 或查看 (Viewed) 过
注意我们不关心 action 为 Ingnored 的广告
结果按 ctr(降序),ad_id(升序)排序

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/ads-performance
//测试数据
Create table If Not Exists Ads (ad_id int, user_id int, action ENUM('Clicked', 'Viewed', 'Ignored'));

insert into Ads (ad_id, user_id, action) values ('1', '1', 'Clicked');
insert into Ads (ad_id, user_id, action) values ('2', '2', 'Clicked');
insert into Ads (ad_id, user_id, action) values ('3', '3', 'Viewed');
insert into Ads (ad_id, user_id, action) values ('5', '5', 'Ignored');
insert into Ads (ad_id, user_id, action) values ('1', '7', 'Ignored');
insert into Ads (ad_id, user_id, action) values ('2', '7', 'Viewed');
insert into Ads (ad_id, user_id, action) values ('3', '5', 'Clicked');
insert into Ads (ad_id, user_id, action) values ('1', '4', 'Viewed');
insert into Ads (ad_id, user_id, action) values ('2', '11', 'Viewed');
insert into Ads (ad_id, user_id, action) values ('1', '2', 'Clicked');

解题思路

Ads表保存了用户对广告的动作。

题目要求:计算每条广告的CTR。

从CTR的计算公式来看,需要计算每条广告的点击数、访问数。

那么,根据广告分组统计即可。只是统计时,需要使用case when子句,对不同的action分别统计。

然后,再根据点击数和访问数,计算ctr即可。

参考SQL

未特别说明的情况下,参考SQL为基于MySQL8.0实现。
select
    ad_id,
    case when sum(case when action in ('Clicked','Viewed') then 1 else 0 end) = 0 then 0.00 
        else round(sum(case when action in ('Clicked') then 1 else 0 end)*100 / sum(case when action in ('Clicked','Viewed') then 1 else 0 end),2) end ctr
from Ads
group by ad_id
order by 2 desc,1;
picture loss