明确题意:
统计每个题目和每份试卷被作答的人数和次数,分别在试卷区和题目区按uv & pv降序显示
问题分解:
- 统计每份试卷被作答的人数和次数,生成子表t_exam_uv_pv:
- 从exam_record抽出每条记录的试卷ID和用户ID
- 按试卷ID分组:GROUP BY exam_id
- 计算uv:count(distinct uid) uv
- 计算pv:count(uid) as pv
- 统计每个题目被作答的人数和次数,生成子表t_practice_uv_pv:
- 从practice_record抽出每条记录的试题ID和用户ID
- 按试卷ID分组:GROUP BY question_id
- 计算uv:count(distinct uid) uv
- 计算pv:count(uid) as pv
- 合并上面记录:UNION ALL
细节问题:
- 表头重命名:as
- 分别按uv & pv降序:ORDER BY uv desc, pv desc
完整代码:
SELECT tid, uv, pv FROM (
SELECT exam_id as tid, count(distinct uid) uv, count(uid) as pv
FROM exam_record
GROUP BY exam_id
ORDER BY uv desc, pv desc
) as t_exam_uv_pv
UNION ALL
SELECT tid, uv, pv FROM (
SELECT question_id as tid, count(distinct uid) uv, count(uid) as pv
FROM practice_record
GROUP BY question_id
ORDER BY uv desc, pv desc
) as t_practice_uv_pv;