简体   繁体   中英

writing subquery in the where clause

I have the following tables

student(student_id, name)
assignment(student_id, course_code, assignment number)

I'm trying to write a query to return those students who have submitted assignment number 1 for a particular course but not assignment number 2

I've written the following query but struggling to itso it returns results on per course basis. Any suggestions?

SELECT name, a.student_id, course_code
FROM assignment a INNER JOIN student s
on a.student_id = s.student_id
WHERE assignment_number = 1
AND assignment_number != 2
SELECT name, a.student_id, course_code
FROM assignment a INNER JOIN student s
on a.student_id = s.student_id
WHERE assignment_number = 1
AND not exists (select * from
                assignment a2 inner join student s2 
                where a2.student_id = s2.student_id
                and s2.student_id = s.student_id
                and a2.assignment_number = 2)

Here's the fiddle to see it in action: http://sqlfiddle.com/#!2/48997/2

SELECT 
  s.name, 
  s.student_id, 
  a.course_code
FROM 
  assignment a 
INNER JOIN 
  student s
ON 
  a.student_id = s.student_id
WHERE 
  assignment_number in( 1,2 ) 
GROUP BY 
  s.name, 
  s.student_id, 
  a.course_code
HAVING max(assignment_number) = 1 

List of students that have completed assignment 1, but not completed assignment 2:

select s.name, a.student_id, a.course_code
from assignment a
inner join student  s on a.student_id = s.student_id
where a.student_id in 
    (Select student_id from assignment
    where assignment_id = 1) -- All students that submitted Assignment 1
and a.assignment_id !=2

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