1

So I have two tables salary and emp whose definition is shown as below

[enter image description here

I am tring to create a query that Find the employee who draws the maximum salary and Display the employee details along with the nationality.

I created this query

select empcode,
       max(basic) as "Highest Sal"
 from salary 
    join emp on empcode;

Please help with this

APC
  • 144,005
  • 19
  • 170
  • 281
MrLazyStudent
  • 13
  • 2
  • 5

3 Answers3

2

Your query uses a simple aggregate max(basic) which would find the highest salary. Except you need to join to the EMP table to display other details. This means you can't use aggregation, because we need to GROUP BY the non-aggregated columns, which would make a nonsense of the query.

Fortunately we can solve the problem with an analytic function. The subquery selects all the relevant information and ranks each employee by salary, with a rank of 1 being the highest paid. We use rank() here because that will handle ties: two employees with the same basic will be in the same rank.

select empcode
           , empname
           , nationality
           , "Highest Sal" 
from (
    select emp.empcode
           , emp.empname
           , emp.nationality
           ,  salary.basic as "Highest Sal" 
           , rank() over (order by salary.basic desc ) as rnk
    from salary join emp on emp.empcode = salary.empcode
)
where rnk = 1;
APC
  • 144,005
  • 19
  • 170
  • 281
1

Find the employee who draws the maximum salary

An employee can have multiple salaries in your datamodel. An employee's (total) salary hence is the sum of these. You want to find the maximum salary per employee and show the employee(s) earning that much.

You can use MAX OVER to find the maximum sum:

select e.*, s.total_salary
from emp e
join 
(
  select
    empcode, 
    sum(basic) as total_salary,
    max(sum(basic)) over () as max_total_salary
  from salary
) s on s.empcode = e.empcode and s.total_salary = s.max_total_salary
order by e.empcode;
Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73
  • Keen piece of observation. I suspect the 1:M relationship is a flaw in the data model rather than an actual business rule. – APC Nov 27 '18 at 10:22
0

Try this:

SELECT * FROM 
(SELECT E.EmpCode, E.EmpName, E.DOB, E.DOJ, E.DeptCode, E.DesgCode, E.PhNo, 
E.Qualification, E.Nationality, S.Basic, S.HRA, S.TA, S.UTA, S.OTRate 
FROM EMP AS E JOIN SALARY AS S ON (E.EmpCode = S.EmpCode) order by S.Basic desc) 
WHERE rownum = 1
KwakuCsc
  • 169
  • 2
  • 4
  • `==` is not valid Oracle syntax. Also this query will not produce a correct solution if there are two employees both earning the highest `basic` salary. – APC Nov 25 '18 at 20:22