I have the following code:
SELECT Credit_book_number, (Last_name + ' ' + First_name + ' ' + Patronymic) AS [Name] FROM Student WHERE EXISTS (SELECT Credit_book_number FROM GradeList g GROUP BY Credit_book_number HAVING MIN(g.Grade) >= 6)
I want to get all the students who have a min grade 6, and I need to do it in subquery in where (most wanted to do it with exists, but not obligatory). My query right now returns all the students, however subquery gets not all of them.
Advertisement
Answer
If just one grade satisfies the condition, then this condition is true for all students, because you do not relate it to the current student.
Change it to
SELECT Credit_book_number, (Last_name + ' ' + First_name + ' ' + Patronymic) AS [Name] FROM Student WHERE Student.Credit_book_number IN ( SELECT Credit_book_number FROM GradeList g GROUP BY Credit_book_number HAVING MIN(g.Grade) >= 6)
Now, only students having a Credit_book_number
with an according number in the GradeList
satisfying the condition are selected.
Another way to make it work, is to add an additional WHERE clause to the sub-select to connect it to the student.
SELECT Credit_book_number, (Last_name + ' ' + First_name + ' ' + Patronymic) AS [Name] FROM Student WHERE EXISTS (SELECT 1 -- It does not matter what we select here FROM GradeList g WHERE g.Credit_book_number = Student.Credit_book_number GROUP BY Credit_book_number HAVING MIN(g.Grade) >= 6)