Wrote a query for this small dataset to find the total score of students.
Conditions:
- Display student total score (top scorer on the top).
- If student gave an exam 2 time than pick the max score.
- if student have max score less than 30 in any subject then remove from output .
— create
CREATE TABLE Student (
id INTEGER PRIMARY KEY auto_increment,
name TEXT NOT NULL,
subject TEXT NOT NULL,
marks int
);
— insert
INSERT INTO Student (name, subject, marks) VALUES ('Rahul', 'Math', 60);
INSERT INTO Student (name, subject, marks) VALUES ('Rahul', 'Science', 60);
INSERT INTO Student (name, subject, marks) VALUES ('Rahul', 'English', 29);
INSERT INTO Student (name, subject, marks) VALUES ('Rahul', 'English', 37);
INSERT INTO Student (name, subject, marks) VALUES ('Nitin', 'Science', 68);
INSERT INTO Student (name, subject, marks) VALUES ('Nitin', 'English', 69);
INSERT INTO Student (name, subject, marks) VALUES ('Nitin', 'Math', 73);
INSERT INTO Student (name, subject, marks) VALUES ('Naveen', 'Math', 60);
INSERT INTO Student (name, subject, marks) VALUES ('Naveen', 'Science', 20);
INSERT INTO Student (name, subject, marks) VALUES ('Naveen', 'English', 29);
INSERT INTO Student (name, subject, marks) VALUES ('Naveen', 'English', 87);
— fetch
SELECT name, sum(score) as totalScore from (
SELECT name, subject, max(marks) as score from Student where name not in (
SELECT name from (
SELECT name, subject, max(marks) as marks from Student group by name, subject
) as abc where marks < 30
) group by name, subject
) as f group by name order by totalScore DESC;
–Output
name totalScore
Nitin 210
Rahul 157
Query mentioned gave correct output but curious to learn if there are any other ways to retrieve the correct output or whether we can optimise this query.
3
Answers
This is an other way to do it using
left join
:First we need to identify students having max score less than 30 in any subject :
Then we will have to eliminate those students by performing a
left join
on this datasett
with a conditiont.name is null
:Then we apply the aggregate function
sum()
to this dataset to get the expected data:Demo here
You can first find the maximum mark for each subject per Student and then use it to filter any Student who has a score of less than 30 to filter out and calculate the sum.
With a CTE
Same thing without CTE
A simple solution without joins is to count subjects with lower marks and exclude the student after the aggregation if lower marks count > 0
DEMO