Got this as an interview question from Amazon to test basic SQL skills and I kind of flopped it. Consider the following tables:
Student - Stid, Stname, Details
Subject - Subid, Subname
Marks - Stid, Subid, mark
Write a query to print the list of names of students who have scored the maximum mark in each subject.
The wrong answer which I gave was:
select A.Stname from A as Student, B as
(select Stid, Subid, max(mark) from Marks groupby Subid) where A.Stid = B.Stid
I was thinking you can have a table B in which you can get the top marks alone and match it with the names in the student table A. But turns out my “groupby” is wrong.
One more variation of the question which I felt was can be asked is that, if there is more than one student having the highest mark in a subject, even their names should be included.
Can you please help solve these queries. They seem to be simple, but I am not able to get a hang of it.
Thanks!
You just have to partition the problem into some bite-sized steps and solve each one by one
First, get the maximum score in each subject:
Then query who are those that has SubjectID with max MarkRate:
Then obtain the Student’s name, instead of displaying just the StudentID:
Database vendors’ artificial differences aside with regards to joining and correlating results, the basic step is the same; first, partition the problem in a bite-sized parts, and then integrate them as you solved each one of them, so it won’t be as confusing.
Sample data:
Live test here: http://www.sqlfiddle.com/#!1/08728/3
IN tuple test is still a join by any other name:
Convert this..
..to JOIN:
Contrast this code with the code immediate it. See how JOIN on independent query look like an IN construct? They almost look the same, and IN was just replaced with JOIN keyword; and the replaced IN keyword with JOIN is in fact longer, you need to alias the independent query’s column result(
max(MarkRate) AS MarkRate) and also the subquery itself (as x). Anyway, this are just matter of style, I prefer IN clause, as the intent is clearer. Using JOINs merely to reflect the data relationship.Anyway, here’s the query that works on all databases that doesn’t support tuple test(
IN):Live test: http://www.sqlfiddle.com/#!1/08728/4