【发布时间】:2010-08-03 06:30:36
【问题描述】:
我有一个表学生(id、姓名、部门、年龄、分数)。我想找到每个部门得分最高(在最年轻的学生中)的最年轻的学生。在 SQL Server 中,我可以使用以下 SQL。
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 中,您不能在子查询中使用 order by 子句,并且没有 limit/top like 关键字。我必须将学生表与自身连接两次才能查询结果。在 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 子句。
-
有一个更简单的解决方案,没有分析功能,请参阅我的问题的公认答案:stackoverflow.com/questions/38180445/…
标签: sql database oracle oracle10g limit