LeetCode-578. 查询回答率最高的问题

从 survey_log 表中获得回答率最高的问题,survey_log 表包含这些列:uid, action, question_id, answer_id, q_num, timestamp。

uid 表示用户 id;action 有以下几种值:"show","answer","skip";当 action 值为 "answer" 时 answer_id 非空,而 action 值为 "show" 或者 "skip" 时 answer_id 为空;q_num 表示当前会话中问题的编号。

请编写SQL查询来找到具有最高回答率的问题。

示例:

输入:
+------+-----------+--------------+------------+-----------+------------+
| uid  | action    | question_id  | answer_id  | q_num     | timestamp  |
+------+-----------+--------------+------------+-----------+------------+
| 5    | show       | 285          | null                 | 1         | 123        |
| 5    | answer    | 285          | 124124          | 1         | 124        |
| 5    | show       | 369          | null                 | 2         | 125        |
| 5    | skip         | 369           | null                 | 2         | 126        |
+------+-----------+--------------+------------+-----------+------------+
输出:
+-------------+
| survey_log  |
+-------------+
|    285      |
+-------------+
解释:
问题285的回答率为 1/1,而问题369回答率为 0/1,因此输出285。

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/get-highest-answer-rate-question

审题:show相当于问题,对于一个问题有回答或者跳过。查询回答率高的问题。就是查询answer_id  不为null的数量。

思考:根据question_id  分组,计算answer_id不为null的所占的比例。

解题:

按question_id分组,每组计算回答率,并按回答率降序。

回答率 = ‘answer’的个数 / ‘show’的个数:

sum(if(S.action='answer',1,0))/sum(if(S.action='show',1,0))
--查询question_id
select S.question_id  as survey_log  from survey_log as S
--按照question_id分组
group by question_id  
--按照回答率降序排序   sum求和函数,
order by sum(if(S.action='answer',1,0))/sum(if(S.action='show',1,0)) desc
--选择第一个
limit 0,1

知识点:

SUM() 函数SUM 函数返回数值列的总数(总额)

发布了84 篇原创文章 · 获赞 2 · 访问量 2640

猜你喜欢

转载自blog.csdn.net/Hello_JavaScript/article/details/103360957