Question : Help On A Trick SQL Query

Hey Guys, here's a SQL query that I need help with, it looks simple, but I can't seem to figure out how to do it:

There are 3 tables:

student(id, gpa)             // id is primary key, unique
studying(deptName, id) //deptName is foreign key of dept table, id is foreign key to student table
dept(deptName)            //deptName is primary key, unique

As you can see, the "studying" table contains value in "dept" table (deptName) and a value in student id. so you may have ("Computer Science", 10),  ("Computer Science", 11), ("Physics", 10),, etc....Where 10, 11 are from the id column of the  "student" table.

In the student table, you may have (10,4.0), (11,,3.9), etc. So these two tables tell us that student ID 10 is studying Computer Science and Physics, and ID 11 is studying Computer Science only.

And "dept" table is just a list of departments like Computer Science, Physics, etc.

Now, I want to do this:

Print each department name, along with the difference in the highest and lowest gpa's of students studying in that department.

So for each dept, I find the max and min GPA's of students in that dept and print out the difference. So each resulting pair is (department Name, GPA difference). If there is only 1 student in any given department, then just give out that student's GPA for that dept.

This sounds simple enough, but any ideas how to do it in one simple SQL? I think it could be done using a combination of Count, Group By, and Having clauses? Sub-queries may be needed of course. But it should not use any temp tables.

Thanks a bunch!



Answer : Help On A Trick SQL Query

1:
2:
3:
4:
5:
select d.deptname, case count(*) when 0 then 0 when 1 then min(s.gpa) else max(s.gpa) - min(s.gpa) end
  from dept d
    left outer join studying ds on d.deptname = ds.deptname
    left outer join student s on ds.id = s.id
  group by d.deptname
Open in New Window Select All
Random Solutions  
 
programming4us programming4us