是否可以在sql中创建动态案例?

时间:2013-12-24 05:55:05

标签: sql

我有这个陈述,其中我会取得学生的成绩。

select concat(students.l_name,', ',students.f_name) as 'Student Name', 
max(case when test_info.test_num =1 then concat(test_results.score,'/',test_info.max_score) end) as 'Quiz #1', 
max(case when test_info.test_num =2 then concat(test_results.score,'/',test_info.max_score) end) as 'Quiz #2', 
max(case when test_info.test_num =3 then concat(test_results.score,'/',test_info.max_score) end) as 'Quiz #3'from test_results 
left join test_info on test_results.test_info_id = test_info.test_info_id 
left join students on test_results.stud_id = students.stud_id 
where test_info.test_type_id = 1 
group by test_results.stud_id order by students.l_name;

现在我的问题是数字测验最终会增加,我必须创建另一个案例陈述,以显示所有等级。有没有可能的方法根据当前的测验总数动态创建案例陈述?

1 个答案:

答案 0 :(得分:0)

你想要它作为额外的列不是吗? sql中没有动态。如果它是Oracle,你可以使用PL / SQL。

另外我觉得,你总是可以按条件在你的组中包含test_info.test_num,所以你只需要一个concat()。

您更新的查询。现在你得到了多行。

select concat(students.l_name,', ',students.f_name) as 'Student Name', 
concat('Quiz #',test_info.test_num) as test_number,
MAX(concat(test_results.score,'/',test_info.max_score)) as  test_results 
left join test_info on test_results.test_info_id = test_info.test_info_id 
left join students on test_results.stud_id = students.stud_id 
where test_info.test_type_id = 1 
group by test_results.stud_id , test_info.test_num
order by students.l_name, test_info.test_num;