I am using SQL (H2 database engine ver 1.4.181) and am trying to sum the top 5 points that a student has. The RESULTS table includes the studentID, eventID and points. Each student can only be entered in an event once. The following subquery is what I am trying to use to do this for the student with and id of 5.
SELECT SUM(points) FROM RESULTS
WHERE eventID IN
(SELECT TOP 5 eventID FROM RESULTS
WHERE studentID = 5 ORDER BY points DESC)
AND studentID = 5;
However, this query is returning null. I have found that, if the ORDER BY points DESC
is removed, then the rest of the query works. Does anyone know how to incorporate the ORDER BY, or why it doesn't work?
Thanks
This looks like a bug in H2. You could use a join. Complete test case:
create table results(eventId int, points int, studentId int);
insert into results values(1, 10, 1), (2, 20, 1), (3, 5, 1);
insert into results values(1, 10, 2), (2, 20, 2), (3, 5, 2);
insert into results values(1, 10, 3), (2, 20, 3), (3, 5, 3);
SELECT SUM(r.points) FROM RESULTS r,
(SELECT eventID FROM RESULTS
WHERE studentID = 2
ORDER BY points DESC
LIMIT 2 ) r2
WHERE r2.eventID = r.eventId
AND studentID = 2;
try using join, you can use sql like this belw
select sum(x.points) from
(select points , event_id from RESULTS) X
(select eventID from
(SELECT eventID, row_number() over (partition by points ORDER BY points DESC ) tops FROM RESULTS ) X
where tops<6 ) Y
where X.eventID=y.eventID
and X.studentID = 5;
Turns out I didn't need an IN query at all. The following worked perfectly:
SELECT SUM(points) FROM
(SELECT TOP 5 points FROM RESULTS
WHERE studentID = 5
ORDER BY points DESC);
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.