I´m having a bad time with a SQL query. I´m using oracle default tables:
\'EMP\' TABLE
http://imageshack.us/photo/my-images/850/sinttuloxps.png/
AND
You can also use the analytical RANK() function:
SELECT * FROM (
SELECT
Dept.DeptNo,
Dept.DName,
Emp.EName,
Emp.Sal,
RANK() OVER (PARTITION BY Dept.DeptNo ORDER BY Emp.Sal DESC) AS DeptSalRank
FROM Emp
INNER JOIN Dept ON Emp.DeptNo = Dept.DeptNo
)
WHERE DeptSalRank = 1
Classic greatest-n-per-group query. Here is what you want:
select dept.dname, emp.empno, emp.ename, emp.sal
from emp
inner join dept on emp.deptno = dept.deptno
inner join
(
select emp.deptno, max(emp.sal) sal
from emp
group by emp.deptno
) ss on emp.deptno = ss.deptno and emp.sal = ss.sal
order by emp.sal desc
Here is a working fiddle: http://sqlfiddle.com/#!4/7147b/6
Additionally, you might want to checkout a different approach. Look here (SQL Select only rows with Max Value on a Column) to see an interesting answer on the topic.
The following query will omit duplicate values
SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO;
The following query will include the duplicate values
SELECT * FROM EMP WHERE (DEPTNO,SAL) IN
( SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO)
As short as the question: SELECT DeptID, MAX(Salary) FROM Employees GROUP BY DeptID