嗨我想要从下面的查询中得到前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