Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Databases SQL Reporting by Example Day 3: Getting Good at Grouping Bus Troubles

Greg Kaleka
Greg Kaleka
39,019 Points

A Simpler Solution to Which Teachers Don't Have a 1st Period Class

The EXCEPT solution is a good one. Just thought I'd share how I did it:

SELECT FIRST_NAME, LAST_NAME, MIN(PERIOD_ID) FROM TEACHERS
JOIN CLASSES ON TEACHERS.ID = CLASSES.TEACHER_ID
GROUP BY TEACHERS.ID
HAVING MIN(PERIOD_ID) > 1

Another alternative...

WITH p1_teachers AS (
  SELECT period_id, teacher_id FROM classes
  WHERE period_id = 1
), list_all AS (
  SELECT * FROM teachers LEFT JOIN p1_teachers ON teachers.id = p1_teachers.teacher_id
)

SELECT first_name, last_name FROM list_all WHERE period_id IS NULL;
Noah Fields
Noah Fields
13,985 Points

I did the following:

SELECT * FROM TEACHERS
WHERE TEACHERS.ID NOT IN
(
  SELECT TEACHERS.ID FROM TEACHERS
  INNER JOIN CLASSES ON CLASSES.TEACHER_ID = TEACHERS.ID
  WHERE CLASSES.PERIOD_ID = 1
);

My version of the solution:

SELECT * FROM TEACHERS WHERE TEACHERS.ID NOT IN (SELECT TEACHER_ID FROM TEACHERS JOIN CLASSES ON CLASSES.TEACHER_ID = TEACHERS.ID WHERE PERIOD_ID = 1)

Ryan Dainton
Ryan Dainton
17,164 Points

A alternate solution with a single subquery and no JOINs:

SELECT *
FROM TEACHERS
WHERE ID NOT IN
(SELECT TEACHER_ID FROM CLASSES WHERE PERIOD_ID = 1);

My solution is similar but easier to read:

SELECT (first_name || " " || last_name) AS "Available Teacher(s) for Morning Bus Duty" FROM TEACHERS
  JOIN CLASSES ON teachers.id = classes.teacher_id
  GROUP BY teachers.id HAVING MIN(classes.period_id) > 1;

2 Answers

Guilherme Mergulhao
Guilherme Mergulhao
4,002 Points

This is how I did it:

SELECT T.FIRST_NAME || ' ' || T.LAST_NAME AS FULLNAME, MIN(C.PERIOD_ID) AS FIRST_PERIOD FROM CLASSES AS C
INNER JOIN TEACHERS AS T ON T.ID = C.TEACHER_ID
GROUP BY FULLNAME HAVING FIRST_PERIOD > 1

SELECT * FROM TEACHERS WHERE id NOT IN (SELECT teacher_id FROM CLASSES WHERE period_id = 1)