IN子查询中的SQL ORDER BY不返回任何结果

时间:2014-10-08 09:21:21

标签: sql subquery sql-order-by h2 sql-in

我正在使用SQL(H2数据库引擎版本1.4.181),我正在尝试将学生的前5分加起来。 RESULTS表包含studentID,eventID和points。每个学生只能参加一次活动。以下子查询是我尝试用于为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,或者它为什么不起作用?

由于

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;

答案 2 :(得分:0)

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

SELECT SUM(points) FROM 
    (SELECT TOP 5 points FROM RESULTS 
        WHERE studentID = 5
        ORDER BY points DESC);