[LeetCode]Get Highest Answer Rate Question

题目描述:

LeetCode 578. Get Highest Answer Rate Question

Get the highest answer rate question from a table survey_log with these columns: uid, action, question_id, answer_id, q_num, timestamp.

uid means user id; action has these kind of values: "show", "answer", "skip"; answer_id is not null when action column is "answer", while are null for "show" and "skip"; q_num is the numeral/order of the question in current session.

Write a sql to identify the question which has the highest answer rate.

Example:

Input:
+------+-----------+--------------+------------+-----------+------------+
| 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        |
+------+-----------+--------------+------------+-----------+------------+
Output:
+-------------+
| survey_log  |
+-------------+
|    285      |
+-------------+
Explanation:
question 285 has answer rate 1/1, while question 369 has 0/1 answer rate, so output 285.

Note: The highest answer rate meaning is: answer number's ratio in show number in the same question.

题目大意:

调查问卷表survey_log ,求action字段中answer / show最大的question_id

解题思路:

全连接(Full Join)

MySQL不支持全连接,可以用LEFT JOIN + RIHGT JOIN模拟

SQL语句:

# Write your MySQL query statement below
SELECT question_id AS survey_log FROM
    (SELECT question_id, COUNT(*) AS answer_count
    FROM survey_log
    WHERE ACTION = 'answer'
    GROUP BY question_id) a
    RIGHT JOIN
    (SELECT question_id, COUNT(*) AS action_count
    FROM survey_log
    GROUP BY question_id) b
    USING (question_id)
    LEFT JOIN
    (SELECT question_id, COUNT(*) AS show_count
    FROM survey_log
    WHERE ACTION = 'show'
    GROUP BY question_id) c
    USING (question_id)
ORDER BY answer_count / show_count DESC
LIMIT 1

 

本文链接:http://bookshadow.com/weblog/2017/05/09/leetcode-get-highest-answer-rate-question/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论