I have two tables which is
Student
ID | Name | Gender | Address |
---|---|---|---|
1 | Abby | Girl | street |
2 | Mark | Boy | street |
3 | Lula | Girl | street |
4 | Bren | boy | street |
Lessons
ID | Lessons_code |
---|---|
3 | MK2234 |
5 | 22324KL |
6 | KCS233 |
and I want to join these tables then get the sum result of the students that didn’t took a lesson then group it by gender like this:
Gender | total |
---|---|
Boy | 2 |
girl | 1 |
I know it use sum()
and left outer join
(?) but I don’t know how to implement it.
Advertisement
Answer
I would suggest not exists
:
select s.gender, count(*) from students s where not exists (select 1 from lessons l where l.id = s.id ) group by s.gender;
You have a very awkward data model. I would expect a column called lessons.id
to refer to the primary key of the lessons
table. Instead. it seems to refer to a student. A better name would be student_id
.