I’m new to SQL and I am having trouble even starting this query.
If a student has a record in ‘2012’, list that record and all of their previous records.
A simplified data set:
ASSIGNMENTS STUDENT_ID BOOK_TITLE TERM
001 MOBY DICK 2009 002 ULYSSES 2009 003 HAMLET 2009 004 1984 2009 005 HAMLET 2009 004 WAR & PEACE 2010 003 THE TRIAL 2010 004 MOBY DICK 2011 001 -NULL---- 2012 004 -NULL---- 2012
Results should be the record of those registered in a given term followed by that student’s previous records. The goal is for the user to look at currently registered students (NULL value in book title) and make sure they don’t assign a book the student has already read.
STUDENT_ID BOOK_TITLE TERM
001 -NULL---- 2012
001 MOBY DICK 2009
004 -NULL---- 2012
004 MOBY DICK 2011
004 WAR & PEACE 2010
004 1984 2009
Any pointers/starting directions would be greatly appreciated! I have tried messing around with 'with', multiple inner joins, but I am not getting anywhere. I keep thinking about if..then syntax that doesn't really work in SQL?
To come up with this answer first I created a query that matched your expected result format. Then I added the where criteria for “only students currently registered”.
If you want to parameterize it put @Term instead of 2012. You could also run it off null book titles using
WHERE BOOK_TITLE IS NULL