How to have multiple condition on one column [closed]

Posted on

Question :

I have table with students – name, id

and table with grades – id, grade value, discipline.

Each students has few grades. I want to select only the students with grade = 2 and grade = 6 in the same time.

SELECT NAME

FROM STUDENTS, GRADES 

WHERE STUDENTDS.ID = GRADES.ID 

AND GRADE = 2 AND GRADE = 6

The logical condition can’t be valid there. Which is the function that I need?

Answer :

SELECT NAME 
FROM STUDENTS s
WHERE EXISTS (SELECT 1 FROM GRADES WHERE ID = s.ID AND GRADE = 2)
    AND EXISTS (SELECT 1 FROM GRADES WHERE ID = s.ID AND GRADE = 6) 

or if you don’t have multiple records for some grades for particular users:

SELECT NAME
FROM STUDENTS
JOIN GRADES ON STUDENTS.ID = GRADES.ID
WHERE GRADE = 2 OR GRADE = 6
GROUP BY ID, NAME
HAVING COUNT(1) = 2

Leave a Reply

Your email address will not be published. Required fields are marked *