Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Greg Kaleka
Greg Kaleka
39,021 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)