我有一個表student(id,name,department,age,score)。我想找到每個部門中擁有最高(年齡最小的學生)分數的最年輕學生。在SQL Server中,我可以使用以下SQL。在Oracle子查詢中排序後得到第一行
select * from student s1
where s1.id in
(select s2.id from student s2
where s2.department = s1.department order by age asc, score desc top 1).
然而,在Oracle中,你不能子句中使用子查詢的順序並沒有像關鍵字沒有限制/頂。我必須自己兩次加入學生表來查詢結果。在oracle中,我使用以下SQL。
select s1.* from student s1,
(select s2.department, s2.age, max(s2.score) as max_score from student s2,
(select s3.department, min(s3.age) as min_age from student s3 group by s3.department) tmp1 where
s2.department = tmp1.department and s2.age = tmp1.min_age group by s2.department, s2.age) tmp2
where s1.department =tmp2.department and s1.age = tmp2.age and s1.score=tmp2.max_score
有沒有人有任何想法來簡化oracle的上述SQL。
在Oracle中,子查詢,你可以* *使用ORDER BY子句。 – 2010-08-03 08:09:09
有一個解決方案更簡單,沒有分析功能,請參閱我的問題的接受答案:http://stackoverflow.com/questions/38180445/oracle-left-join-very-big-table-and-limit-the-joined -row-to-one-the-large – Dany 2016-07-05 05:14:25