I have 3 tables: Course, Professor, Degree.
The course table lists all courses being taught and the professor who is assigned to teach it using the professor ID. The professor table lists all the professors along with their general contact information. It's primary key is the professor ID. The degree table lists all the degrees held by professors using their professor ID as a foreign key.
The problem I am having is that when I want a listing of each course along with the assigned professor and whether that professor has a doctorate degree. If they do return a “Y” if not return an “N”. I only want one result per professor despite there being multiple entries for each professor in the table.
ProfessorID Professor
01 Mary Smith
02 Harry Johnson
03 Teddy Fitz
04 Larry Manson
05 Sarah Love
CourseID CourseName ProfessorID
001 Math 101 01
002 English 201 01
003 English101 02
004 Math 101 03
005 Science 101 04
DegreeID Degree Doctorate Degree ProfessorID
0001 BA N 01
0002 MS N 01
0003 PHD Y 01
0004 BA N 02
0005 MS N 02
0006 BA N 03
0007 MS N 03
0008 EDD Y 03
0009 BA N 04
The Results I would like is:
Course Professor Doctorate
Math 101 Mary Smith Y
English 201 Mary Smith Y
English101 Harry Johnson N
Math 101 Teddy Fitz Y
Science 101 Larry Manson N
However, I keep getting a result for each degree that the professor has; regardless of whether it is a doctorate or not. Such as the following:
Course Professor Doctorate
Math 101 Mary Smith Y
Math 101 Mary Smith N
English 201 Mary Smith Y
English 201 Mary Smith N
English101 Harry Johnson N
Math 101 Teddy Fitz Y
Science 101 Larry Manson N
How should I code this?
There are different ways of fixing it. Given the final result table, you can use a statement similar to the following to get the result you are looking for:
SELECT Course, Professor, MAX(Doctorate) as Doctorate
FROM YOUR_RESULTING_TABLE
GROUP BY Course, Professor
the MAX() function on letters return based on the lexicographic(alphabetical) order.
There are lots of ways to achieve what you want. I'll site 2 examples:
You can use LEFT JOIN
+ COALESCE
, since those professor without doctorate can be default to 'N':
SELECT
A.CourseName,
B.Professor,
COALESCE(C.Doctorate, 'N')
FROM course_table as A
LEFT JOIN professor_table as B
ON A.ProfessorID = B.ProfessorID
LEFT JOIN degree_table as C
ON B.ProfessorID = C.ProfessorID AND C.Doctorate = 'Y'
UPDATED:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.