简体   繁体   中英

MySQL how to select records of a field doesn't have all required values

In MySQL, how to select the records with a specific field doesn't cover all required values?

for example, in the following records, some students finished continuous numbered assignments, like s1 finished from 1 to 5, s4 finished from 1 to 7, but s1 and s4 had different MAX NUMBER of assignments. While some students finished NON-CONTINUOUS numbered assignments, eg s2 and s3. how to select the students who have finished CONTINUOUS NUMBERED assignments, regardless the max number?

[[More condition, sorry!]] I need one more column and condition to meet my real work, for example, "failed" column, where 1 means failed, 0 means passed.

Together with the original condition, I also want to exclude those students who have failed one or more assignments, that is, failed must be 0.

In the following records with failed column added, I only want to select student 1, because student 4 has failed assignment (although his assignments number are also continuous)

id student_id assignment_done failed

1 s1 1 0

2 s1 2 0

3 s1 3 0

4 s1 4 0

5 s1 5 0

6 s2 2 0

7 s2 4 0

8 s3 1 0

9 s3 5 0

10 s4 1 0

11 s4 2 0

12 s4 3 0

13 s4 4 0

14 s4 5 0

15 s4 6 0

16 s4 7 1

Select student_id from STUDENT group by student_id having count( assignment_done) = max(assignment_done);
+------------+
| student_id |
+------------+
| s1         |
| s4         |
+------------+
2 rows in set (0.00 sec)

Try this:

SELECT student_id, 
       COUNT(CASE failed
             WHEN '0' THEN 1
             ELSE NULL
             END) as failedCount
FROM #yourTableName(e.g, students) 
GROUP BY student_id
HAVING COUNT(assignment_done) = MAX(assignment_done)
   AND
       MAX(assignment_done)=failedCount;

In a simple way you can use below sql query

SELECT distinct student_id FROM Students A
WHERE A.student_id in (
    SELECT S.student_id
    FROM Students S
    GROUP BY S.student_id
    HAVING COUNT(*) =5
)

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