LeetCode:Database 82.广告效果

Posted Xiao Miao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Database 82.广告效果相关的知识,希望对你有一定的参考价值。

要求:写一条SQL语句来查询每一条广告的 ctr ,ctr 要保留两位小数。结果需要按 ctr 降序、按 ad_id 升序 进行排序。

ctr=

表: 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') 。

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 |
+-------+---------+---------+

Result Table:

+-------+-------+
| 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(升序)排序

SQL语句:

#1.方法1
select ad_id,round(ifnull(sum(if(action='clicked',1,0))/sum(if(action='ignored',null,1)),0.00)*100 ,2)as ctr
from ads 
group by ad_id
order by ctr desc,ad_id asc;
#2.方法2
with a as(
select ad_id,round(sum(if(action='clicked',1,0))/count(user_id)*100,2) as ctr
from ads
where action='clicked' or action='viewed'
group by ad_id)

select * from(
select * from a
union all
select distinct ad_id,0.00 as ctr
from ads 
where ad_id not in (select ad_id from a))b
order by ctr desc,ad_id asc;

以上是关于LeetCode:Database 82.广告效果的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(数据库)- 广告效果

LeetCode:Database 55.报告的记录 II

HTML连载82-努比亚界面顶部区域和广告区域

LeetCode Solution-82

LeetCode第82场双周赛

LeetCode第82场双周赛