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

文章目录

  • [1 题目描述](#1 题目描述)
  • [2 测试用例](#2 测试用例)
  • [3 解题思路](#3 解题思路)

1 题目描述

SurveyLog 表:

sql 复制代码
+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| action      | ENUM |
| question_id | int  |
| answer_id   | int  |
| q_num       | int  |
| timestamp   | int  |
+-------------+------+

这张表可能包含重复项.

action 是一个 ENUM(category) 数据, 可以是"show", "answer" 或者"skip".

这张表的每一行表示: ID = id 的用户对 question_id 的问题在 timestamp 时间进行了 action 操作.

如果用户对应的操作是"answer", answer_id 将会是对应答案的 id, 否则, 值为 null.

q_num 是该问题在当前会话中的数字顺序.

回答率 是指: 同一问题编号中回答次数占显示次数的比率.

编写一个解决方案以报告回答率 最高的问题. 如果有多个问题具有相同的最大回答率 , 返回 question_id 最小的那个

2 测试用例

输入:

SurveyLog table:

sql 复制代码
+----+--------+-------------+-----------+-------+-----------+
| id | 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       |
+----+--------+-------------+-----------+-------+-----------+

输出:

sql 复制代码
+------------+
| survey_log |
+------------+
| 285        |
+------------+

解释:

问题 285 显示 1 次, 回答 1 次. 回答率为 1.0

问题 369 显示 1 次, 回答 0 次. 回答率为 0.0

问题 285 回答率最高

3 解题思路

  1. 使用 sum() if() 分组统计 question_id 状态为 showanswer 数量信息
sql 复制代码
select question_id,
       sum(if(action = 'answer', 1, 0)) as answerSum,
       sum(if(action = 'show', 1, 0))   as showSum
from SurveyLog
group by question_id;

查询结果

question_id answerSum showSum
285 1 1
369 0 1
  1. 计算 question_id 的回答率, 对数据进行排序 ratio desc, question_id asc
sql 复制代码
select question_id,
       sum(if(action = 'answer', 1, 0)) / sum(if(action = 'show', 1, 0)) as ratio
from SurveyLog
group by question_id
order by ratio desc, question_id asc;

查询结果

question_id ratio
285 1.0000
369 0.0000
  1. 回答率在最终答案中不要求展示, 将回答率的计算放在 order by
sql 复制代码
select question_id as survey_log
from SurveyLog
group by question_id
order by sum(if(action = 'answer', 1, 0)) / sum(if(action = 'show', 1, 0)) desc, question_id asc
limit 1;

查询结果

survey_log
285
相关推荐
J_bean10 分钟前
剖析 MySQL InnoDB 共享行锁 (S) & 排他行锁 (X)
数据库·mysql·共享行锁·s lock·排他行锁·x lock
技术长镜头32 分钟前
别再只说“走 B+Tree”:一条 SQL 在 InnoDB 中的完整寻址过程
后端·mysql
LuminousCPP1 小时前
单链表专题(四)-刷题复盘篇-LeetCode 138 随机链表复制|原地拷贝法突破复杂指针操作
数据结构·笔记·算法·leetcode·链表
Forever Nore1 小时前
LeetCode 14 最长公共前缀 - 纵向扫描
linux·服务器·leetcode
圣保罗的大教堂2 小时前
leetcode 3090. 每个字符最多出现两次的最长子字符串 简单
leetcode
一只fish15 小时前
优化器架构对比:Oracle vs PostgreSQL vs MySQL
mysql·postgresql·oracle
旖旎夜光15 小时前
LeetCode 3:无重复字符的最长子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
Navigator_Z17 小时前
LeetCode //C - 1192. Critical Connections in a Network
c语言·算法·leetcode
rannn_11118 小时前
【力扣hot100】链表专题下|138、148、23、146
java·算法·leetcode·链表·开发
hanlin0319 小时前
刷题笔记:力扣第189题-轮转数组
笔记·算法·leetcode