我有三张桌子,如下所示。
TABLE1 : tb_subject
subject_id subject_name
1 English
2 Maths
3 Science
Table2 : tb_student
subject_id student_id
1 AA
1 BB
2 CC
3 DD
3 EE
Table3 : tb_student_score
student_id score conducted_month_number
AA 20 2
BB 30 3
CC 50 4
AA 80 4
DD 50 6
BB 10 2
EE 40 3
结果应为
conducted_month_number SUM(subject_id1) SUM(subject_id2) SUM(subject_id3)
1 0 0 0
2 30 0 0
3 30 0 40
4 80 50 0
5 0 0 0
6 0 0 60
7 0 0 0
8 0 0 0
9 0 0 0
10 0 0 0
11 0 0 0
12 0 0 0
如何为此编写选择查询?可以在结果输出中添加未存储在表中的所有月份编号吗?
答案 0 :(得分:3)
您应该可以使用case when
分别为每个主题求和:
SELECT conducted_month_number,
SUM(CASE b.subject_id WHEN 1 THEN a.score ELSE 0 END) AS English,
SUM(CASE b.subject_id WHEN 2 THEN a.score ELSE 0 END) AS Maths,
SUM(CASE b.subject_id WHEN 3 THEN a.score ELSE 0 END) AS Science
FROM tb_student_score AS a
JOIN tb_student AS b ON b.student_id = a.student_id
GROUP BY conducted_month_number
ORDER BY conducted_month_number;
然而,单凭这一点并不能确保您获得的conducted_month_number
值不存在 - 如果这是一个问题,您可以创建一个每月得分为0的虚拟学生
编辑:我注意到在我提交答案的同时发布了一些评论 - 如果你想根据tb_subject表中行的值来改变求和列的数量,你将找不到{的关系模型{1}}非常适合这项任务。但是,您可以轻松返回并更新您的查询,以包含您稍后可能添加的任何新主题。
答案 1 :(得分:3)
使用SQL
添加了1到12个月的dummy values
,之后又添加了union statement
来计算总分。
试试这个: -
group by