示例 :question_practice_detail
id | device_id | question_id | result |
1 | 2138 | 111 | wrong |
2 | 3214 | 112 | wrong |
3 | 3214 | 113 | wrong |
4 | 6543 | 114 | right |
5 | 2315 | 115 | right |
6 | 2315 | 116 | right |
7 | 2315 | 117 | wrong |
示例:user_profile
id | device_id | gender | age | university | gpa | active_days_within_30 | question_cnt | answer_cnt |
1 | 2138 | male | 21 | 北京大学 | 3.4 | 7 | 2 | 12 |
2 | 3214 | male | 复旦大学 | 4.0 | 15 | 5 | 25 | |
3 | 6543 | female | 20 | 北京大学 | 3.2 | 12 | 3 | 30 |
4 | 2315 | female | 23 | 浙江大学 | 3.6 | 5 | 1 | 2 |
5 | 5432 | male | 25 | 山东大学 | 3.8 | 20 | 15 | 70 |
6 | 2131 | male | 28 | 山东大学 | 3.3 | 15 | 7 | 13 |
7 | 4321 | female | 26 | 复旦大学 | 3.6 | 9 | 6 | 52 |
- select a.device_id,
- a.question_id,
- a.result
- from question_practice_detail a
- left join user_profile b
- on a.device_id = b.device_id
- where university = '浙江大学'
根据示例,你的查询应返回以下结果,查询结果根据question_id升序排序:
用户信息表 user_profile,其中device_id指终端编号(认为每个用户有唯一的一个终端),gender指性别,age指年龄,university指用户所在的学校,gpa是该用户平均学分绩点,active_days_within_30是30天内的活跃天数。
device_id | gender | age | university | gpa | active_days_within_30 |
2138 | male | 21 | 北京大学 | 3.4 | 7 |
3214 | male | NULL | 复旦大学 | 4 | 15 |
6543 | female | 20 | 北京大学 | 3.2 | 12 |
2315 | female | 23 | 浙江大学 | 3.6 | 5 |
5432 | male | 25 | 山东大学 | 3.8 | 20 |
2131 | male | 28 | 山东大学 | 3.3 | 15 |
4321 | male | 28 | 复旦大学 | 3.6 | 9 |
答题情况明细表 question_practice_detail,其中question_id是题目编号,result是答题结果。
device_id | question_id | result |
2138 | 111 | wrong |
3214 | 112 | wrong |
3214 | 113 | wrong |
6543 | 111 | right |
2315 | 115 | right |
2315 | 116 | right |
2315 | 117 | wrong |
5432 | 118 | wrong |
5432 | 112 | wrong |
2131 | 114 | right |
5432 | 113 | wrong |
- --伪代码:
- select a.university,
- sum(b.question_id)/count( b.device_id) as avg_answer_cnt
- from user_profile a
- left join question_practice_detail b
- on a.device_id = b.device_id
- group by university
-
-
- --不严谨但正确代码:
- select a.university,
- count(b.question_id)/count(distinct b.device_id) as avg_answer_cnt
- from user_profile a
- join question_practice_detail b
- on a.device_id = b.device_id
- group by university
-
-
- --严谨正确代码:
- select a.university,
- round(count(b.question_id)/count(distinct b.device_id),4) as avg_answer_cnt
- from user_profile a
- join question_practice_detail b
- on a.device_id = b.device_id
- group by a.university
- order by a.university
-
- --语法:order by colunm_name(s) ASC|DESC
- -- 例:order by ID ASC,name ASC,sex DESC
- --不写就是默认升序,DESC降序
请你写SQL查找每个学校用户的平均答题数目(说明:某学校用户平均答题数量计算方式为该学校用户答题总次数除以答过题的不同用户个数)根据示例,你的查询应返回以下结果(结果保留4位小数),注意:结果按照university升序排序!!!
university | avg_answer_cnt |
北京大学 | 1.0000 |
复旦大学 | 2.0000 |
山东大学 | 2.0000 |
浙江大学 | 3.0000 |