0

我正在使用 SQL(H2 数据库引擎版本 1.4.181)并试图总结学生的前 5 分。RESULTS 表包括 studentID、eventID 和积分。每个学生只能参加一次活动。以下子查询是我尝试为 id 为 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;

但是,此查询返回 null。我发现,如果ORDER BY points DESC删除了 ,那么查询的其余部分就可以工作。有谁知道如何合并 ORDER BY,或者为什么它不起作用?

谢谢

4

3 回答 3

2

这看起来像 H2 中的错误。您可以使用连接。完整的测试用例:

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;
于 2014-10-08T13:36:26.093 回答
0

尝试使用join,你可以像这样使用sql

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;
于 2014-10-08T09:53:25.933 回答
0

原来我根本不需要 IN 查询。以下工作完美:

SELECT SUM(points) FROM 
    (SELECT TOP 5 points FROM RESULTS 
        WHERE studentID = 5
        ORDER BY points DESC);
于 2014-10-09T01:28:04.657 回答