Skip to content
Advertisement

How to join 3 tables and get the field with 2 different conditions?

I have 3 tables: Students, Courses (important field Points), StudentCourses (important field Grade).

The exam is passed if Grade is greater than or equal to 70, so student will receive Points. If Grade is less than 70, student will not receive Points. Student is graduated if sum of his credits is greater than 10.

I need to select StudentName, sum of his PASSED Points, average of his ALL grades. I could select StudentName, sum of his PASSED Points and average of his PASSED grades. But I need average of ALL grades.

I wrote the following query.

Advertisement

Answer

Although you want to select only the student’s name make sure that you group by student’s id also (I believe there is a column in the Students table) becaus ethere would be 2 students with the same name.
You must not use this condition:

because this will remove the rows with Grade < 70 which you need to calculate the average.
So the sum of creditpoints will be calculated with a CASE statement:

Since you are using SQL Server you can’t use the alias CreditPoints in the HAVING clause so you have to repeat the CASE statement.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement