嗨我想要從下面的查詢中得到前3名總和(薪金),沒有重複。 我們不能使用rownum,因爲它會給出重複。有人可以幫我嗎?SQL查詢 - 前3總和(sal)
SELECT d.dname, SUM(e.sal)
FROM emp e ,dept d
WHERE e.deptno = d.deptno
GROUP BY d.dname;
嗨我想要從下面的查詢中得到前3名總和(薪金),沒有重複。 我們不能使用rownum,因爲它會給出重複。有人可以幫我嗎?SQL查詢 - 前3總和(sal)
SELECT d.dname, SUM(e.sal)
FROM emp e ,dept d
WHERE e.deptno = d.deptno
GROUP BY d.dname;
select dname,sum(distinct sal) from
(SELECT d.dname dname, sal,
dense_rank() over (partition by e.deptno order by sal desc) rn
FROM emp e,dept d WHERE e.deptno = d.deptno) where rn<=3 group by dname;
例如:
dname sal rn
..... ... ...
acc 5000 1
acc 3000 2
acc 3000 2
acc 2000 3
bcc 4500 1
bcc 3000 2 .....etc
如果通過工資降序排列它過濾的薪水,然後ROWNUM應該工作:
select *
from (select d.dname, sum(e.sal)
from emp e, dept d
where e.deptno = d.deptno
group by d.dname
order by 2 desc)
where rownum <= 3
在外部查詢中也使用不同的函數來避免重複的總和。
select distinct(a.sumsal),a.dname
from (select d.dname, sum(e.sal)
from emp e, dept d
where e.deptno = d.deptno
group by d.dname
order by 2 desc) a
where rownum <= 3;
http://www.techonthenet.com/oracle/questions/top_records.php – MatBailie