2014-10-08 85 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);