异常的邮件的概率题解

异常的邮件概率

http://www.nowcoder.com/questionTerminal/d6dd656483b545159d3aa89b4c26004e

要想到题目要求求的是  正常用户发送邮件失败的数目/正常用户发送邮件总数目,所以必然要连接user表排除掉黑名单用户,
所以第一时间写出来的是:
select xxx 
from email
join user as u1 on (email.send_id=u1.id and u1.is_blacklist=0)
join user as u2 on (email.receive_id=u2.id and u2.is_blacklist=0)
这样就联立user表并且排除掉了所有黑名单用户,然后就是找到日期,和每个日期邮件发送的成功率,日期就select email.date就行了,但是成功率不太好写,我们这里用一个函数叫case....when ..then ...else ...end
就很简单了,如下:
sum(case email.type when'completed' then 0 else 1 end)
    
这个代码的意思就是,当email.type为completed时,就为0,如果不为completed就为1,然后把这一列所有的和加起来,我们就得到了失败的发送邮件的数目,然后使用round函数保留后面3位:
round
(
    sum(case email.type when'completed' then 0 else 1 end)*1.0/count(email.type),3
) 
最后再按照日期分组,得到每一天的数据,并且按照日期升序排序:
group by email.date order by email.date;

联立所有sql得:
select email.date, round(
    sum(case email.type when'completed' then 0 else 1 end)*1.0/count(email.type),3
) as p
from email
join user as u1 on (email.send_id=u1.id and u1.is_blacklist=0)
join user as u2 on (email.receive_id=u2.id and u2.is_blacklist=0)
group by email.date order by email.date;







全部评论
其实用AVG更简单一些:ROUND(AVG(CASE WHEN type = 'completed' THEN 0 ELSE 1 END),3) AS p
10 回复 分享
发布于 2022-02-16 15:03
您好,请问为什么要join user表两次呢?为什么不可以 email e join user u on e.send_id=u.id and e.receive_id=u.id?
1 回复 分享
发布于 2021-05-12 20:33
select date, count(distinct case when type='completed' then email.id else null end )as success, count(distinct case when type='no_completed' then email.id else null end )as fail, round(count(distinct case when type='no_completed' then email.id else null end )/ count(distinct case when type='completed' then email.id else null end ) ,3)as p from email left join user u1 on email.send_id=u1.id and u1.is_blacklist=0 left join user u2 on email.receive_id=u2.id and u2.is_blacklist=0 group by date order by date; MySQL里运行是的 但是牛客网上报错 我觉得没错啊
点赞 回复 分享
发布于 2022-10-26 00:52 美国
我喜欢你这个 JOIN 语法,有点 sqllist 的感觉
点赞 回复 分享
发布于 2022-02-24 09:51
这边能不能直接用avg呢。。
点赞 回复 分享
发布于 2022-02-07 12:15
大佬,请问为什么最后要group by date呢?
点赞 回复 分享
发布于 2022-01-06 22:11
要U2是要干嘛呢
点赞 回复 分享
发布于 2021-12-22 16:39
大佬你好,请问这里的CASE...WHEN...换成IF函数为什么会报错呢?
点赞 回复 分享
发布于 2021-12-08 16:19
为什么sum后边要*1.0呢
点赞 回复 分享
发布于 2020-10-29 15:49
想问一下为什么换成left join 就不对了呢
点赞 回复 分享
发布于 2020-09-08 02:20

相关推荐

06-07 00:00
已编辑
腾讯_后端开发
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
128
7
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务