2014-10-08 82 views
0

我正在使用SQL(H2数据库引擎版本1.4.181),并试图总结学生拥有的前5个点。 RESULTS表包含studentID,eventID和点。每个学生只能参加一次活动。以下子查询是我正在尝试为具有5且id为5的学生执行此操作。IN子查询中的SQL ORDER BY返回无结果

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,或者为什么它不起作用?

感谢

+1

你使用什么数据库系统,它是什么版本? – 2014-10-08 09:29:48

+0

“点”列是否有空值? – 2014-10-08 11:29:05

回答

0

尝试使用连接时,可以使用这样的SQL 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; 
+1

我越来越: '语法错误在SQL语句“SELECT SUM(X.POINTS)FROM (选择点,EVENTID结果中的)X ([*] SELECT EVENTID FROM (SELECT EVENTID,ROW_NUMBER()OVER(分数按积分顺序降分结果)× 哪里上方<6)是否 其中X.EVENTID = Y.EVENTID AND X.STUDENTID = 32179“; [42000-181] 42000/42000' – Jess 2014-10-08 10:20:30

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; 
0

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

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