[英]Get the top row after order by in Oracle Subquery
我有一個表學生(身份證,姓名,部門,年齡,分數)。 我想找到每個系最高(最年輕的學生)得分最年輕的學生。 在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。
試試這個
select * from
(SELECT id, name, department, age, score,
ROW_NUMBER() OVER (partition by department order by age desc, score asc) srlno
FROM student)
where srlno = 1;
除了艾倫的回答,這也很好:
select *
from (SELECT *
FROM student
order by age asc,
score desc)
where rownum = 1;
除了Bharat的回答之外,還可以在Oracle的子查詢中使用ORDER BY來做到這一點(正如Jeffrey Kemp指出的那樣):
SELECT *
FROM student s1
WHERE s1.id IN (SELECT id
FROM (SELECT id, ROWNUM AS rn
FROM student s2
WHERE s1.department = s2.department
ORDER BY age ASC, score DESC)
WHERE rn = 1);
如果您使用此方法,您可能想要刪除子查詢,只需使用rownum = 1
。 這將導致不正確的結果,因為排序將在標准之后應用(您將獲得已排序的1行,而不是排序集中的一行)。
select to_char(job_trigger_time,'mm-dd-yyyy') ,job_status from
(select * from kdyer.job_instances ji INNER JOIN kdyer.job_param_values pm
on((ji.job_id = pm.job_id) and (ji.job_spec_id = '10003') and (pm.param_value='21692') )
order by ji.job_trigger_time desc)
where rownum<'2'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.