如何在查询

时间:2018-03-22 06:07:49

标签: mysql sql sql-server database null

我希望根据category_id显示所有考试记录。 每个主题都有2个类别ID。如果结果中没有category_id个检查结果,如何显示结果?
我想在null存在时在某些列和某些值上显示category_id 这张图片将让您清楚地了解我想要问的内容。 提前谢谢。

select er.subject_id,er.student_id,er.class_id,
 ec.exam_catagory_name,er.catagory_id, er.exam_type_id, sum( er.marks_obtained) subject_marks_obtained, sum(er.total_marks) subject_total_marks from Exam_Results er
join Exam_Subjects es on er.subject_id=es.subject_id
join Exam_Catagories ec on ec.exam_catagory_id=er.catagory_id
where er.student_id=2369 and er.session_id=81 and er.class_id=265
 and er.subclass_id=182 and er.term_id=148 and er.shift_id=35 
group by er.student_id,er.subject_id,er.class_id,er.catagory_id,er.exam_type_id
,er.term_id,ec.exam_catagory_name
 order by er.subject_id

输出:

Output Result Image

有20条记录,但我想要27条记录同时进行检查和评估,标记为null。如何显示subject_id的考试和评估记录,并在商标中提供null

提前致谢。

3 个答案:

答案 0 :(得分:0)

您应该使用case声明:

case when category_id = 51 then null else subject_marks_obtained end [subject_marks_obtained],
case when category_id = 51 then null else subject_total_marks end [subject_total_marks]

答案 1 :(得分:0)

join Exam_Catagories ec on ec.exam_catagory_id=er.catagory_id

请尝试使用以下脚本部分,而不是查询的上方部分。

left join Exam_Catagories   ec on ec.exam_catagory_id=er.catagory_id and ec.exam_catagory_id in (51,52)

答案 2 :(得分:0)

在Exam_Catagories使用左连接,因此在Exam_Results中的记录将显示甚至与考试类别ID不匹配