I'm using MySQL 8.0.21
I am trying to calculate how many rows within a given table meet the necessary requirements. In this case, I want to count how many distinct 'student_id' rows there are in a 'class_id' per date, but I can only consider a 'student_id' if all the 'grade' of that 'student_id' equals 0. Also, I can only consider it if 'active' = TRUE.
for this query, I would expect a result like this: enter image description here
Query to build database is here:
create table students (
dt_reference DATE,
CLASS_ID number(10),
STUDENT_ID number(10),
GRADE number(10),
ACTIVE boolean
);
insert into students values ('2022-10-10', 1, 100, 10,TRUE);
insert into students values ('2022-10-10', 1, 100, 0,TRUE);
insert into students values ('2022-10-10', 1, 100, 0,TRUE);
insert into students values ('2022-10-11', 1, 100, 0,TRUE);
insert into students values ('2022-10-11', 1, 100, 0,TRUE);
insert into students values ('2022-10-10', 2, 101, 5,TRUE);
insert into students values ('2022-10-10', 2, 101, 2,TRUE);
insert into students values ('2022-10-12', 2, 102, 0,FALSE);
insert into students values ('2022-10-12', 2, 102, 0,FALSE);
insert into students values ('2022-10-13', 3, 103, 0,TRUE);
insert into students values ('2022-10-13', 3, 100, 0,TRUE);
insert into students values ('2022-10-13', 3, 100, 5,TRUE);
The Query I did to get this information is that:
SELECT STUDENT_ID, CLASS_ID, DATE, GRADE, ACTIVE
FROM students X
WHERE NOT EXISTS (
SELECT 1
from students Y
WHERE Y.STUDENT_ID = X.STUDENT_ID
and Y.CLASS_ID = X.CLASS_ID
and Y.DATE = X.DATE
and Y.GRADE = 0
and Y.ACTIVE = TRUE