简体   繁体   中英

Multiple filters SQL

Lets say I have 2 tables.
First table is Classroom :

-ClassroomID

Second table is Students .

-StudentID

-ClassroomID (References Classroom)

-Age

-Score (integer)

I am trying to return rows of students where 2 conditions pass: The student age is <10, AND, in the student's class, the sum of all students score is < 100.

My current query is

SELECT StudentID, ClassroomID 
FROM Students 
WHERE EXISTS (SELECT *, SUM(Score) FROM StudentID GROUP BY ClassroomID HAVING score < 100)

but this just returns the entire table, and I cannot figure out how to get the age condition working.

For the 2nd condition group by classroomid and set it in the HAVING clause:

select * 
from students
where age < 10 
and classroomid in (
  select classroomid
  from students
  group by classroomid
  having sum(score) < 100
)

You can do it this way:

SELECT StudentID
     , ClassroomID 
  FROM Students a 
 WHERE EXISTS 
       ( SELECT 1 
           FROM Students b 
          Where B.Age < 10 
            and a.StudentID = b.StudentID
          GROUP  
             BY ClassroomID HAVING SUM(Score) < 100)

Nb: have pb formatting the code properly, sorry

SELECT s.*
FROM Students s
NATURAL JOIN ( SELECT ss.ClassroomID 
               FROM Students ss
               GROUP BY ss.ClassroomID 
               HAVING SUM(ss.Score) < 100 ) sss
WHERE s.Age < 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM