2017-02-11 34 views
0

每組最大值從下表中(稱爲學生):查找PostgreSQL中

name course mark  
A  a   100 
A  c   78 
A  d   83 
B  a   79 
B  b   91 
C  c   78 
C  d   65 
D  a   75 

我試圖找到名字,其中最高分是當然「a'.So在這種情況下, A和D應該在答案中,但我的查詢似乎只報告所有學生的最高分數:

SELECT name 
FROM Student 
WHERE mark >= all 
    (SELECT mark FROM Student WHERE course='a'); 

我在哪裏出錯了?

+1

編輯您的問題並顯示結果。 –

回答

1

你是如此接近!只要移動一下,你就很好。不需要任何複雜的東西。

SELECT name 
FROM Student s 
WHERE course = 'a' AND mark >= all 
    (SELECT mark FROM Student WHERE name = s.name); 
0

這似乎是row_number()工作:

select s.* 
from (select s.*, 
      row_number() over by (partition by name order by mark desc) as seqnum 
     from student s 
    ) s 
where seqnum = 1;