2014-02-17 47 views
1

嗨我想要從下面的查詢中得到前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; 
+1

http://www.techonthenet.com/oracle/questions/top_records.php – MatBailie

回答

0

你可以試試下面的查詢:

Select 
    Agg_Sal.Dname, 
    Agg_Sal.Total_Sal, 
    Rank() Over (Partition By Dname Order By Total_Sal Desc) Rank 
From 
    (Select 
    D.Dname Dname, 
    Sum(Sal) As Total_Sal 
    From 
    Emp E, Dept D 
    Where 
    E.Deptno = D.Deptno 
    Group By 
    D.Dname) Agg_Sal 
Where 
    Rank <= 3 
Order By 
    Rank 

這是一個類似上例中的Here

+0

此查詢不會工作 – Sai

1
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和也通過使用dense_rank()函數我已經給despon命令deepno明智的薪水行號

例如:

dname sal rn 
..... ... ... 
acc 5000 1 
acc 3000 2 
acc 3000 2 
acc 2000 3 
bcc 4500 1 
bcc 3000 2 .....etc 
  • 外,我只是用不同的關鍵字
+0

一些解釋將有助於未來的用戶瞭解你的答案 – Machavity

+0

@Machavity解釋加 – Sai

0

如果通過工資降序排列它過濾的薪水,然後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 
0

在外部查詢中也使用不同的函數來避免重複的總和。

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;