我对我正在尝试运行的sql代码有些怀疑。首先,我有2个表格没有讨论:
当然
students_course
我需要执行“课程”表的选择,但我必须计算“students_course”中的行,如果它对应于同一个课程并且状态等于3,则将结果添加到“number_students_enrolled”列中我不知道如何组合select语句并将结果添加到第一个表中。
示例,我有一个课程,有9名学生注册,但在“students_course”表中存在另外3行属于同一课程ID,并且状态等于3,所以我必须计算它然后添加它到number_students_enrolled列并显示最终结果,在这种情况下它将是12.你能帮助我尝试解决这个问题吗?谢谢!
一些示例数据:
当然
id_course - name_course - date_begin - date_finish - number_students_enrolled
150 - maths - 02/10/16 - 04/10/16 - 9
172 - economy - 02/14/16 - 05/08/16 - 21
students_course
id_student - id_course - state
10 - 150 - 3
12 - 150 - 3
13 - 150 - 3
14 - 150 - 1
15 - 194 - 2
16 - 194 - 3
选择后我必须获得以下结果
id_course - name_course - date_begin - date_finish - number_students_enrolled
150 - maths - 02/10/16 - 04/10/16 - 12
172 - economy - 02/14/16 - 05/08/16 - 21
答案 0 :(得分:1)
这应该适合你:
SELECT c.name_course,c.number_students_enrolled+(SELECT count(sc2.id_student)
FROM dbo.students_course sc2 WHERE sc2.id_course=c.id_course
AND sc2.state =3) FROM dbo.course c
答案 1 :(得分:0)
不考虑您已经有 number_students_enrolled 列,我正在给您一个查询。希望它有所帮助。
select C.id_course, C.name_course,
(select count(1)
from students_course
where id_course = C.ID
and state = 3) as call_as_you_need_this_column
from course C
order by C.id_course
这只是达到你需要的一种方式。
答案 2 :(得分:0)
此查询将为您提供已注册学生的数量:
select c.id_course, count(*) as students_enrolled
from course c join student_course sc on c.id_course = sc.id_course
group by id_course;
如果你想要“预先计算,我会建议一个观点。”
答案 3 :(得分:0)
尝试此查询以获取结果
SELECT c.id_course,c.name_course,c.date_begin,c.date_finish,
(NVL(temp.cnt, 0)+c.number_students_enrolled)
FROM course c
left join (SELECT count(sc.id_student) as cnt,sc.id_course as course_id
FROM students_course sc WHERE sc.state =3 group by sc.id_course ) as temp
on temp.course_id =c.id_course