美文网首页
Leetcode578.查询回答率最高的问题(中等)

Leetcode578.查询回答率最高的问题(中等)

作者: kaka22 | 来源:发表于2020-07-10 23:10 被阅读0次

    题目
    从 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。

    解答
    回答率 = 'answer'的个数 / 'show'的个数
    对question_id 进行分组统计answer和show的个数

    select S.question_id, sum(if(S.action = 'show', 1, 0)) as num_show,  sum(if(S.action = 'answer', 1, 0)) as num_answer
    from survey_log as S
    group by S.question_id 
    

    num_answer/num_show 即为回答率 按这个进行降序取出第一个即可

    select S.question_id as survey_log
    from survey_log as S
    group by S.question_id 
    order by sum(if(S.action = 'answer', 1, 0))/sum(if(S.action = 'show', 1, 0))  desc
    limit 0,1;
    

    相关文章

      网友评论

          本文标题:Leetcode578.查询回答率最高的问题(中等)

          本文链接:https://www.haomeiwen.com/subject/mqtvcktx.html